thread cannot see changes to shared data

Top  Previous  Next

shared variables may need to be volatile


The compiler may arrange for a variable's value to be held in a register. If so, changes to that variable would be invisible to another thread. If you declare the variable as volatile, the compiler keeps the variable in memory. This is only necessary when the variable is accessed concurrently by two or more threads.

 

Note that even if you use volatile you may still need to use semaphores as well to synchronise the threads' access to a shared variable.