Just a simple example. No need to explain lock
, Interlocked
and so on.
The bool signals whether a value for state
is available. state
and the bool is not further modified afterwards.
int state;
volatile bool stateAvailable;
Thread A:
while(!stateAvailable) { sleep }
read state
Thread B:
state = 5;
stateAvailable = true;
Does this ensure that Thread A will always read the state correctly? I'm confused about the guarantees here (only for this simple example):
- Will a volatile write ensure that operations before will have happened and the volatile read ensure that the operations after will not have happened, thereby also syncing processor state?
- Or, will the volatile write/read only make sure that the compiler does not optimize away the bool-check from Thread A and it having no impact on the possibly stale value of
state
?
If you can point me to a duplicate of this question I'd be grateful as well.