Tuesday, August 9, 2016

Volatile

2 Threads sync the variable, e.g. Thread 1 set true, the true value will bring to Thread 2.
if without volatile , the step 3 will not run, and stop in while loop. (Run in Release Mode)

 private volatile bool _loop = true;

 static void Main(string[] args)
 {
     Program test1 = new Program();
     Thread obj = new Thread(SomeThread);
     obj.Start(test1);

     Thread.Sleep(200);
     test1._loop = false;
     Console.WriteLine("Step 2 : Value is set to False");
 }

 private static void SomeThread(object o1)
 {
     Program o = (Program)o1;
     Console.WriteLine("Step 1 - Enter Loop");
     while (o._loop)
     {
     }
     Console.WriteLine("Step 3 - Exit Loop");
 }

No comments:

Post a Comment