Reputation: 355
I want to know, if trying to update a boolean value being used by a thread is guaranteed to be successful, without any lock protection.
like the following case: there wont be any problem for Stop() to change the boolean member of m_ThreadActive, while threadproc is running?
private bool m_ThreadActive = true;
public void threadproc
{
while (m_ThreadActive)
{
...
}
}
public void Stop()
{
m_ThreadActive = false;
}
Upvotes: 1
Views: 624
Reputation: 109587
It is theoretically possible that the compiler could optimise the loop in such a way that the loop variable always remains true.
To ensure that can't happen, use a Volatile.Read()
:
while (Volatile.Read(ref ThreadActive))
If you don't have a version of .Net which supports Volatile.Read()
you could declare m_ThreadActive
as volatile
:
private volatile bool m_ThreadActive = true;
Or, better, use Thread.MemoryBarrier()
:
while (ThreadActive)
{
Thread.MemoryBarrier();
// ...
}
See my answer here for a program that demonstrates a requirement for volatile
, Volatile.Read()
or Thread.MemoryBarrier()
for it to work correctly.
For more information on why the use of the volatile
keyword can be a bit suspect, see this article from Eric Lippert.
Upvotes: 6