Skip to main content
gamedev.net
🔒 Locked

threading, volatile var

Started by likeafox 1 reply 800+ views
Original Post
likeafox
likeafox
(using C++) I've started to get into multithread programming, and I'm wondering if I am properly protecting my data from being corrupted across threads. Until now I've been using the volatile keyword for certain shared variables. But I'm not convinced it helps. say I have a local variable, x, in my wannabe thread-safe function that counts how many time the funcion is called: void dosomething() { volatile static int x = 0; x++; } I'm no expert on reading assembly, but I outputted the function to asm and the x++ part looked like 1 movl _ZZ11dosomethingvE1x, %eax 2 incl %eax 3 movl %eax, _ZZ11dosomethingvE1x In that case, if two concurrent threads call this function, given the nature of multithreading couldn't they be executed in this order?: thread 1: 1 movl _ZZ11dosomethingvE1x, %eax 2 incl %eax thread 2: 1 movl _ZZ11dosomethingvE1x, %eax 2 incl %eax 3 movl %eax, _ZZ11dosomethingvE1x thread 1: 3 movl %eax, _ZZ11dosomethingvE1x So after calling the function twice, might it be that x is only incremented once? I think I may be missing the point of volatile. If so, how can I get around this problem?
"It compiles! Ship it!"
Brother Bob
Brother Bob
You are correct; the code is not thread safe. You cannot really achieve thread safety in general using methods running ontop of the threading system only. You need something to prevent the other thread from running at that point, and only the threading system itself can guarantee that.

Check out mutexes, critical sections, or whatever mechanisms are available on your platform to synchronize threads.
Vorpy
Vorpy
volatile only ensures that the memory is actually read or written. In some cases reads and writes can be optimized away or cached in registers, and this is what the volatile keyword is meant to avoid. In the case of multiple threads altering a value you'll need to use mutexes or a similiar synchronization mechanism to ensure that the reads and writes take place in the correct order.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.