Let’s say we have this simple class:
class example
{
bool m_isCanceled;
example() : m_isCanceled(false) {}
public:
void cancel() { m_isCanceled = true; }
void doWork()
{
for (int i = 0; i < MAX_RETRIES; ++i)
{
// Slow
doStuff();
if (m_isCanceled)
{
return;
}
}
}
}
If we call example::doWork() on one thread, and then, after a while we call example::cancel() on another, is there a bound on how long until the first thread will see that m_isCanceled is now true?
In a similar situation, I suggested we protect m_isCanceled with a mutex, but my co-worker said that the first thread would see the update after an extra iteration, at most. Is this right?
There is no guarantee at all. Ideally you would make the boolean variable atomic. Failing that, making it
volatilehappens to work on pretty much all known platforms. Of course protecting it with a mutex is guaranteed to work.In practice, it will “happen to work” anyway. The implementation generally won’t know if
doStuff, or some function it calls, manipulatesm_isCancelled. So it won’t be able to keep it in a register or something across those calls.