It's simply just not valid code :wink: :P
If you're sharing a mutable variable between threads, then you
need to use some form of synchronization, such as wrapping it in a mutex.
Assuming C/C++: The old-school advice would be: this will work fine if 'done' is
volatile, but don't do that (
it's not what volatile is for, and will still be buggy). You can, however, make done a
std::atomic and it will work in this particular scenario. An atomic variable is basically one that's wrapped in a super-lightweight, hardware-accelerated mutex, and by default is set to provide "sequentially consistent ordering" of memory operations.
Without some for of synchronization being present, there's no guarantee that changes to memory made by one thread will be visible by another thread at all, or in the correct order.
Ordering matters a lot in most cases, e.g. let's say we have:
result = 0
done = false
Worker:
result = 42; // do some work
done = true; // publish our results to main thread
Main:
Launch Worker
while(!done) {;} // busy wait
print( result );
If implemented correctly, this code should print '42'.
But, if memory ordering isn't enforced by the programmer (by using a synchronization primitive), then it's possible that Main sees a version of memory where done==true, but result==0 -- i.e. the memory writes from Worker have arrived out of order.
Synchronization primitives solve this. e.g. the common solution would be:
mutex
result = 0
done = false
Worker:
lock(mutex)
{
result = 42;
done = true;
}
Main:
Launch Worker
while(1)
{
lock(mutex)
{
if done then break;
}
}
print( result );
Or the simplest atomic version... which honestly you should only try to use after doing a lot of study on the C++11 memory model and the x86 memory model (and the memory models of other processors...) because it's easy to misunderstand and have incorrect code :(
result = 0
done = false
Worker:
result.AtomicWrite(42, sequential_consistency)
done.AtomicWrite(true, sequential_consistency)
Main:
Launch Worker
while(!done.AtomicRead(sequential_consistency)) {;} // busy wait
print( result.AtomicRead(sequential_consistency) )