"The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times."
using System;
using System.Threading;
public class Worker
{
// This method is called when the thread is started.
public void DoWork()
{
while (!_shouldStop)
{
Console.WriteLine("Worker thread: working...");
}
Console.WriteLine("Worker thread: terminating gracefully.");
}
public void RequestStop()
{
_shouldStop = true;
}
// Keyword volatile is used as a hint to the compiler that this data
// member is accessed by multiple threads.
private volatile bool _shouldStop;
}
public class WorkerThreadExample
{
static void Main()
{
// Create the worker thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
// Start the worker thread.
workerThread.Start();
Console.WriteLine("Main thread: starting worker thread...");
// Loop until the worker thread activates.
while (!workerThread.IsAlive) ;
// Put the main thread to sleep for 1 millisecond to
// allow the worker thread to do some work.
Thread.Sleep(1);
// Request that the worker thread stop itself.
workerObject.RequestStop();
// Use the Thread.Join method to block the current thread
// until the object's thread terminates.
workerThread.Join();
Console.WriteLine("Main thread: worker thread has terminated.");
}
// Sample output:
// Main thread: starting worker thread...
// Worker thread: working...
// Worker thread: working...
// Worker thread: working...
// Worker thread: working...
// Worker thread: working...
// Worker thread: working...
// Worker thread: terminating gracefully.
// Main thread: worker thread has terminated.
}
Another article contain following about Volatile keyword
The point of volatile is that multiple threads running on multiple CPU's can and will cache data and re-order instructions.
If it is not volatile, and CPU A increments a value, then CPU B may not actually see that incremented value until some time later, which may cause problems.
If it is volatile, this just ensures the 2 CPU's see the same data at the same time. It doesn't stop them at all from interleaving their reads and write operations which is the problem you are trying to avoid
Reference:http://msdn.microsoft.com/en-us/library/vstudio/x13ttww7.aspx
http://stackoverflow.com/questions/154551/volatile-vs-interlocked-vs-lock
No comments:
Post a Comment