Why do we have to make the assumption that *lock is NOT register allocated?
InnerLight
Given simple code like this, the compiler may likely optimize the code such that lock is allocated as a register. If it does so, then a change to lock by another thread won't actually be reflected in another one, since the threads are not going to memory for reading (instead, they just visit a register).
So in general, global variables shared in a multithreaded application should be declared to the compiler to be volatile so that it won't put it in a register.
jc2
In fact, you can actually enforce that a variable should not register allocated by using the keyword volatile.
Why do we have to make the assumption that *lock is NOT register allocated?
Given simple code like this, the compiler may likely optimize the code such that lock is allocated as a register. If it does so, then a change to lock by another thread won't actually be reflected in another one, since the threads are not going to memory for reading (instead, they just visit a register).
So in general, global variables shared in a multithreaded application should be declared to the compiler to be volatile so that it won't put it in a register.
In fact, you can actually enforce that a variable should not register allocated by using the keyword volatile.