Jac*_*ada 3 .net c# concurrency multithreading
我不明白为什么在这个实现stopped不是volatile- 如果一个不同的线程更新这将正确反映?
其次是testing(!Stopping)原子?
using System;
using System.Threading;
/// <summary>
/// Skeleton for a worker thread. Another thread would typically set up
/// an instance with some work to do, and invoke the Run method (eg with
/// new Thread(new ThreadStart(job.Run)).Start())
/// </summary>
public class Worker
{
/// <summary>
/// Lock covering stopping and stopped
/// </summary>
readonly object stopLock = new object();
/// <summary>
/// Whether or not the worker thread has been asked to stop
/// </summary>
bool stopping = false;
/// <summary>
/// Whether or not the worker thread has stopped
/// </summary>
bool stopped = false;
/// <summary>
/// Returns whether the worker thread has been asked to stop.
/// This continues to return true even after the thread has stopped.
/// </summary>
public bool Stopping
{
get
{
lock (stopLock)
{
return stopping;
}
}
}
/// <summary>
/// Returns whether the worker thread has stopped.
/// </summary>
public bool Stopped
{
get
{
lock (stopLock)
{
return stopped;
}
}
}
/// <summary>
/// Tells the worker thread to stop, typically after completing its
/// current work item. (The thread is *not* guaranteed to have stopped
/// by the time this method returns.)
/// </summary>
public void Stop()
{
lock (stopLock)
{
stopping = true;
}
}
/// <summary>
/// Called by the worker thread to indicate when it has stopped.
/// </summary>
void SetStopped()
{
lock (stopLock)
{
stopped = true;
}
}
/// <summary>
/// Main work loop of the class.
/// </summary>
public void Run()
{
try
{
while (!Stopping)
{
// Insert work here. Make sure it doesn't tight loop!
// (If work is arriving periodically, use a queue and Monitor.Wait,
// changing the Stop method to pulse the monitor as well as setting
// stopping.)
// Note that you may also wish to break out *within* the loop
// if work items can take a very long time but have points at which
// it makes sense to check whether or not you've been asked to stop.
// Do this with just:
// if (Stopping)
// {
// return;
// }
// The finally block will make sure that the stopped flag is set.
}
}
finally
{
SetStopped();
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
此代码来自Jon Skeet撰写的文章.
因为它只是在里面访问过lock.A lock 还可以确保您查看最新值.
重新原子性(我假设你真的意味着在这里同步?); 它没有任何可能性; 即使Stopping是同步的,一旦我们退出,我们就不能再相信价值是最新的lock.因此!Stopping没有或多或少的同步Stopping.重要的是我们知道我们最近至少检查过了.有一个边缘情况,我们检查后就会改变标志,但这很好:当我们检查时,我们应该继续这样做.