Click here to Skip to main content
11,706,024 members (54,146 online)
Click here to Skip to main content

The unsung hero, Volatile keyword: - C# threading

, 23 May 2012 CPOL 47.5K 24
Rate this:
Please Sign up or sign in to vote.
The unsung hero, Volatile keyword: - c# threading My mad and blind love with c# threadingWhen I first saw c# threading code, I just falled in love forever. As days passed by the power and simplicity of “System.Threading” namespace converted my love in to blind

My mad and blind love with C# threading

 When I first saw c# threading code, I just falled in love forever. As days passed by the power and simplicity of “System.Threading” namespace converted my love in to blind love.

Thread t1 = new Thread(SomeThread);
t1.Start(o1);

 

In case you have not still fallen in love and new to C# threading, you can start looking at my C# training threading video. 















 

 

 

The blind love was but obvious because in today’s modern world parallel task execution is compulsory component.My love helped me to please users with mind blowing UI interfaces, multi-threaded batch processes, until one day…..

End of blind love with C# threads











But one fine day my love with c# thread’s had a bump.I had two threads running and both where updating the same local variable.  The updation done by one thread was not visible to the other thread.

Let me detail what I am saying. I had create a local variable called as “_loop” as shown in the below abstract code snippet. This variable was set to ‘true’ by default.

class Program
{

bool _loop = true;

…        
}

 

In the same application I had created one function called as “SomeThread” which will run until the “_loop” is true.

 

private static void SomeThread(object o1)
{
….
….
while (o._loop)
{}
}

From the main thread I was spawning this some thread which was running the loop continuously. In this main thread I was setting the “_loop” to false. In other words the infinite loop of “SomeThread” should stop and exit…VOILA it did not.

static void Main(string[] args)
{
Thread t1 = new Thread(SomeThread);
t1.Start(o1);
o1._loop = false;
….
….
}

Below is the complete source code, you download and see it for yourself.

bool _loop = true;
static void Main(string[] args)
{
            Program o1 = new Program();
            Thread t1 = new Thread(SomeThread);
            t1.Start(o1);
            Thread.Sleep(2000);
            o1._loop = false;
            Console.WriteLine("Value Set to false");
}
        private static void SomeThread(object o1)
        {
            Program o = (Program)o1;
            Console.WriteLine("Loop Starting...");
            while (o._loop)
            {}
            Console.WriteLine("Loop Stopping...");
        }

If you run the above code you can see the infinite loop starting, but I does not end even if the value was set to “false”.


You can also see the actual video demo of the code by clicking on c# training for threading .

Note :- When you run the code ensure that you have selected release  with CNTRL + F5 pressed.

  

 

Why did my love ditch me:- Local Thread memory storage and synchronization


After so many years of successful relationship it was difficult to believe this unexpected behavior. So I started googling to get reasons for it.

After long hours of reading, I was stunned that there are two kinds of memory we have to deal when it comes to threading.

One is the main memory where our variables are allocated and the thread also has his own local memory…SURPRISED, same here.

In other words the “_loop” is present at three places one in the main memory and second in the local memories of “mainthread” and “somethread” functions.

When the program kick starts the “_loop” is set to true. So all the memory storages have “_loop” set to true. See the below visual representation.
As the program runs the main thread set the value to false. This updation is done in the local memory of “mainthread” and main the memory, but it does not update the local memory of “SomeThread”. So the “SomeThread” function still sees the stale value and keeps running in a loop.
Below is a visual representation of how things look internally at various points.

 

 

 

 

 

 

 

 

 

 

 

The unsung hero: - Volatile keyword



All relationships have problem, we just need to adjust, find solution and move with life. I was definitely in no mood of leaving c# threading after such a wonderful relationship.

The solution to get around this multiple memory storages was “VOLATILE” keyword.

If you declare your variable as volatile the thread tries to access values from main memory rather than from his local memory where data is stale. It does slow down a bit but it addresses this big confusion.

See it yourself, take the same source code and change the “_loop” variable to volatile as shown in the below code snippet and run it.

 

class Program
{
  volatile bool _loop = true;


Ensure that you select mode “release” and hit control + f5 to see the expected behavior.

 



 

 

 

Feel and See it yourself

In case you want to see it live what I have said in this blog see the video below

<OBJECT type="application/x-shockwave-flash" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=3,0,0,0" WIDTH="640" HEIGHT="360" data="http://www.youtube.com/v/DZUXDSEuqek?version=3&feature=player_detailpage"></OBJECT>

You can also see it yourself by downloading the code from the below link.

I am trainer by profession, interested in C# training, click here C# training.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Shivprasad koirala
Architect http://www.questpond.com
India India

I am an ex-Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos, writing books and corporate trainings. Do visit my site for 
.NET, C#, Design Pattern, WCF, Silverlight, LINQ, ASP.NET, ADO.NET, SharePoint, UML, SQL Server  training 
and Interview questions and answers


You may also be interested in...

Comments and Discussions

 
QuestionMy Vote of 5 Pin
Member 1064025720-May-15 0:50
memberMember 1064025720-May-15 0:50 
QuestionWithout volatile also I am achieving results Pin
Member 1119224026-Jan-15 14:22
memberMember 1119224026-Jan-15 14:22 
GeneralNice article and great discussions Pin
Shanadas27-Nov-14 0:30
memberShanadas27-Nov-14 0:30 
GeneralMy vote of 5 Pin
abhi.shrotriya31-Oct-14 22:09
memberabhi.shrotriya31-Oct-14 22:09 
GeneralMy vote of 1 Pin
hungndv23-Sep-14 19:50
memberhungndv23-Sep-14 19:50 
QuestionRegarding Release Mode Pin
Member 1065313122-Sep-14 6:16
memberMember 1065313122-Sep-14 6:16 
Questionresult is different than yours Pin
tomar virender9-May-14 2:00
membertomar virender9-May-14 2:00 
GeneralMy vote of 5 Pin
Phani K27-Mar-14 23:00
memberPhani K27-Mar-14 23:00 
GeneralMy Vote for 5 Pin
rajneeshrai10-Dec-13 1:32
professionalrajneeshrai10-Dec-13 1:32 
GeneralMy vote of 5 Pin
sudeep_nigam8-May-13 2:21
membersudeep_nigam8-May-13 2:21 
GeneralMy vote of 1 Pin
Member 63815-Apr-13 16:00
memberMember 63815-Apr-13 16:00 
GeneralMy vote of 1 Pin
Matty224-Apr-13 15:37
memberMatty224-Apr-13 15:37 
QuestionNot working Pin
Member 879811415-Oct-12 17:31
memberMember 879811415-Oct-12 17:31 
GeneralMy vote of 2 Pin
Björn Friedrich30-Jun-12 4:49
memberBjörn Friedrich30-Jun-12 4:49 
GeneralMy vote of 2 Pin
johannesnestler30-May-12 21:12
memberjohannesnestler30-May-12 21:12 
QuestionVideo capture Pin
Anand K Reddy27-May-12 20:49
memberAnand K Reddy27-May-12 20:49 
GeneralMy vote of 5 Pin
surajfrommumbai24-May-12 5:30
membersurajfrommumbai24-May-12 5:30 
GeneralMy vote of 1 Pin
Leonardo Paneque24-May-12 3:49
memberLeonardo Paneque24-May-12 3:49 
GeneralRe: My vote of 1 Pin
Shivprasad koirala24-May-12 5:27
memberShivprasad koirala24-May-12 5:27 
GeneralRe: My vote of 1 Pin
Leonardo Paneque24-May-12 5:55
memberLeonardo Paneque24-May-12 5:55 
GeneralRe: My vote of 1 Pin
Shivprasad koirala24-May-12 15:20
memberShivprasad koirala24-May-12 15:20 
GeneralRe: My vote of 1 Pin
Leonardo Paneque25-May-12 4:37
memberLeonardo Paneque25-May-12 4:37 
GeneralRe: My vote of 1 Pin
Theraot24-Oct-12 20:07
memberTheraot24-Oct-12 20:07 
GeneralRe: My vote of 1 Pin
oggenok24-May-12 19:00
memberoggenok24-May-12 19:00 
GeneralRe: My vote of 1 Pin
Shivprasad koirala24-May-12 20:49
memberShivprasad koirala24-May-12 20:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150819.1 | Last Updated 23 May 2012
Article Copyright 2012 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid