In a multithreaded C++ program, I have the equivalent of this running in one thread:
while(obj->member) { } // waiting for obj->member to be set to false in another thread
and in another thread, obj->member is set to false. Even when it’s set to false, however, the loop doesn’t break. If I change it to this:
while(obj->member) { Sleep(1) }
It works as expected and breaks when obj->member is set to false in the other thread.
Why does it work like this?
Try making member
volatile. This will force it to be fetched from memory each time it is used, rather than from a CPU register (which is how the compiler might optimise it.)