Che*_*ing 0 .net c# concurrency multithreading thread-safety
我想知道,如果尝试更新线程使用的布尔值,则保证成功,没有任何锁定保护.
类似下面的情况:当threadproc正在运行时,Stop()更改m_ThreadActive的布尔成员不会有任何问题吗?
private bool m_ThreadActive = true;
public void threadproc
{
while (m_ThreadActive)
{
...
}
}
public void Stop()
{
m_ThreadActive = false;
}
Run Code Online (Sandbox Code Playgroud)
从理论上讲,编译器可以优化循环,使循环变量始终保持为真.
为确保不会发生,请使用Volatile.Read():
while (Volatile.Read(ref ThreadActive))
Run Code Online (Sandbox Code Playgroud)
如果您没有支持的.Net版本,Volatile.Read()可以声明m_ThreadActive为volatile:
private volatile bool m_ThreadActive = true;
Run Code Online (Sandbox Code Playgroud)
或者,更好,使用Thread.MemoryBarrier():
while (ThreadActive)
{
Thread.MemoryBarrier();
// ...
}
Run Code Online (Sandbox Code Playgroud)
见我的答案在这里的演示要求的程序volatile,Volatile.Read()或者Thread.MemoryBarrier()为它正常工作.
有关为什么使用volatile关键字有点可疑的更多信息,请参阅Eric Lippert的这篇文章.