I have an int foo variable that is accessed from two threads. Assuming that I have no problems with the race conditions (access is protected by the mutex, all operations are atomic or some other way of protecting against race conditions), there is still the problem of “register caching” (due to the lack of a better name), where the compiler may assume that if a variable is read twice without writing between them, it is the same value and therefore can "optimize" things like:
while(foo) { // <-may be optimized to if(foo) while(1) do-something-that-doesn't-involve-foo; }
or
if(foo) // becomes something like (my assembly is very rusty): mov ebx, [foo]; cmp ebx, 0; jz label; do-something-that-doesn't-involve-foo; do-something-else-that-doesn't-involve-foo; if(foo) // <-may be optimized to jz label2; do-something;
makes a mark foo how volatile solve this problem? Are changes from one thread guaranteed to reach another thread?
If not, what other way to do this? I need a solution for Linux / Windows (possibly standalone solutions), not C ++ 11.
c ++ c multithreading volatile
baruch
source share