Wednesday, May 14, 2008

C# - Volatility and the Volatile Keyword

I am doing impact analysis regarding changes I need to make on a code base pretty late in the development cycle.    I came across an older piece of code I wrote that uses the C# volatile keyword.  It got me thinking about how and why I was using volatile to the point where I became unsure of my original implementation (that's always scary at the end of a development cycle).  I started to read up on volatile...

First, read MSDN's description here: http://msdn.microsoft.com/en-us/library/x13ttww7(VS.71).aspx.

Then read MSDN's .NET Framework 3.5 treatment on the topic here: http://msdn.microsoft.com/en-us/library/x13ttww7.aspx

Read the about a thread termination scheme using volatile here: http://msdn.microsoft.com/en-us/library/7a2f3ay4.aspx

This statement is important:

"The use of volatile with the _shouldStop data member enables you to safely access this member from multiple threads without the use of formal thread synchronization techniques, but only because _shouldStop is a bool. This means that only single, atomic operations are necessary to modify _shouldStop. If, however, this data member were a class, struct, or array, accessing it from multiple threads would likely cause intermittent data corruption..."

...ONLY SINGLE, ATOMIC OPERATIONS ARE NECESSARY TO MODIFY... 

Okay, that makes great sense but what is happening underneath the .NET covers?    Why use volatile instead of a lock?  Is volatile just a convenience for serializing accesses to simple data types or does it mean something more?   Are there better or more efficient constructs to use over volatile?

For answers, I read the following:

http://www.yoda.arachsys.com/csharp/threads/volatility.shtml

http://blogs.msdn.com/brada/archive/2004/05/12/130935.aspx

http://discuss.develop.com/archives/wa.exe?A2=ind0203B&L=DOTNET&P=R375

http://www.bluebytesoftware.com/blog/2007/06/09/ALazyInitializationPrimitiveForNET.aspx

My conclusion: while my use of volatile does what I intended it to, I will use locks or some sort of signaling mechanism from this point forward.

No comments:

Disclaimer

Content on this site is provided "AS IS" with no warranties and confers no rights. Additionally, all content on this site is my own personal opinion and does not represent my employer's view in any way.