Sign in to follow this  
likeafox

threading, volatile var

Recommended Posts

(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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this