Is atomic operation enough?

class StopIt { private bool stop; void Loop() { while (!stop) { // work } } void Stop() { stop = true; } } 

Basically, if the Loop method works in one thread and Stop is called from another, will the operation be stopped correctly? I understand that reading / writing bool is atomic. But, is that enough? If the thread cycle does not stop immediately, problems arise. Should I mark a stop to volatility?

+7
c #
source share
1 answer

Yes, you should definitely mark stop as volatile.

Atomicity is not enough - this does not guarantee that one thread will ever β€œsee” changes made by another.

While my understanding of volatile is currently undergoing some kind of operation, you might think about writing a volatile variable like "make sure others can see it right away!" and reading from a mutable variable like "I want to see the last value!"

Without stop volatile, this loop can continue forever, even if Stop() is called in another thread. Basically, a JIT can read a variable into a register quite reasonably, and then just read from the register forever.

In fact, if β€œwork” is ever associated with calling a non-inline method, I believe that JIT is currently forced to do volatile reads anyway, but this is just the current practical limitation ... theory says you should make it volatile.

+10
source share

All Articles