Monday, 30 December 2019

C# - Thread Volatile

Two separate thread. First thread is default main program thread and the second one is child thread which we started by initiate a new Thread instance in our code.
Update CheckStatus as false in our main method, thread update their local variable value and Sync that into main memory location. The problem is the CheckStatus in the child thread are not updated in their local memory accordingly.
We can understand when we work with multiple threads, all threads have their own local memory and any update in local memory sync with main memory but that will be not reflected in other threads local memory. So, when multiple thread working on common variables it will create problem. 
*Use volatile Keyword to Fix Problems With Reading/Writing Shared Data.

Microsoft Doc

The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. The compiler, the runtime system, and even hardware may rearrange reads and writes to memory locations for performance reasons. Fields that are declared volatile are not subject to these optimizations. Adding the volatile modifier ensures that all threads will observe volatile writes performed by any other thread in the order in which they were performed. There is no guarantee of a single total ordering of volatile writes as seen from all threads of execution.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Volatile
{
    public class MainThreadProgram
    {
        volatile bool CheckStatus = true;
        static void Main(string[] args)
        {
            MainThreadProgram mainthread = new MainThreadProgram();
            Thread childThread = new Thread(() => ChildThread(mainthread));
            childThread.Start();
            Thread.Sleep(5000);
            mainthread.CheckStatus = false;
            Console.WriteLine("Change CheckStatus false");
        }

        private static void ChildThread(MainThreadProgram objProgram)
        {
            Console.WriteLine("Child Thread Loop Starting...");
            while (objProgram.CheckStatus)
            {
            }
            Console.WriteLine("Child Thread Loop Stopping...");
        }

    }
}

No comments:

Post a Comment