c# multi-threaded volatile

concept

The volatile keyword indicates that a field may be modified by multiple concurrently executing threads.

The compiler, the runtime system, and even the hardware may rearrange reads and writes to memory locations for performance reasons.

Fields declared volatile are excluded from certain types of optimizations.

sample

public class Worker
{
    // This method is called when the thread is started.
    public void DoWork()
    {
        bool work = false;
        while (!_shouldStop)
        {
            work = !work; // simulate some work
        }
        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
{
    public 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 500 milliseconds to
        // allow the worker thread to do some work.
        Thread.Sleep(500);

        // 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: terminating gracefully.
    // Main thread: worker thread has terminated.
}

Adding the volatile modifier to the declaration of _shouldStop always gives the same result.
However, without this modifier on the _shouldStop member, the behavior is unpredictable. The DoWork method may optimize member access, resulting in reads of stale data.
Given the nature of multithreaded programming, the number of times stale data is read is unpredictable. Different program runs will produce some different results.

Volatile class

  • On multiprocessor systems, a Volatile Write operation ensures that the value written to a memory location is immediately visible to all processors. A Volatile Read operation obtains the most recent value written to a memory location by any processor. These operations may require flushing of processor caches, which may affect performance.

  • On uniprocessor systems, Volatile reads and writes ensure that values ​​are read or written to memory and not cached (for example, in processor registers). Therefore, you can use these operations to synchronize access to fields that can be updated by another thread or by hardware.

Guess you like

Origin blog.csdn.net/a_codecat/article/details/128462294