<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
		>
<channel>
	<title>Comments on: Volatile keyword in C# – memory model explained</title>
	<atom:link href="http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/feed/" rel="self" type="application/rss+xml" />
	<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/</link>
	<description>On programming, technology, and random things of interest</description>
	<lastBuildDate>Sun, 05 Sep 2010 10:59:03 +0000</lastBuildDate>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
	<item>
		<title>By: Brian Gideon</title>
		<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/comment-page-1/#comment-1086</link>
		<dc:creator>Brian Gideon</dc:creator>
		<pubDate>Mon, 23 Aug 2010 19:23:03 +0000</pubDate>
		<guid isPermaLink="false">http://igoro.com/?p=468#comment-1086</guid>
		<description>This is one of the better explanations of the .NET memory model I have see. You have a done a great job describing the behavior using the &quot;thread cache&quot; illustration. Joe Albahari has a great &lt;a href=&quot;http://www.albahari.com/threading/part4.aspx&quot; rel=&quot;nofollow&quot;&gt;write up&lt;/a&gt; on the topic as well, but uses the instruction reordering terminology. The astute reader of both can appreciate how they compliment each other.</description>
		<content:encoded><![CDATA[<p>This is one of the better explanations of the .NET memory model I have see. You have a done a great job describing the behavior using the &#8220;thread cache&#8221; illustration. Joe Albahari has a great <a href="http://www.albahari.com/threading/part4.aspx" rel="nofollow">write up</a> on the topic as well, but uses the instruction reordering terminology. The astute reader of both can appreciate how they compliment each other.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Igor Ostrovsky</title>
		<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/comment-page-1/#comment-1053</link>
		<dc:creator>Igor Ostrovsky</dc:creator>
		<pubDate>Tue, 27 Jul 2010 06:52:42 +0000</pubDate>
		<guid isPermaLink="false">http://igoro.com/?p=468#comment-1053</guid>
		<description>Hi Matt,

The safe thing to do would be to publish the Test object by writing it into a volatile field.

1.    The writer first writes all fields on the Test object, and then writes the reference to the Test object into a volatile field.

2.    The reader first reads the reference from a volatile field, and then reads fields of the Test object.

If the object is published via a volatile field, the reader cannot possibly observe the state of the object before it was initialized by the constructor. An alternative solution is to write the object it into a regular field under a lock, and then read it under the same lock.

HOWEVER, in today&#039;s .NET implementation on today&#039;s hardware, I understand that you may be able to get away with removing the volatile modifier on the publication field, even though I would recommend against doing that. For example, Vance Morrison&#039;s article (http://msdn.microsoft.com/en-us/magazine/cc163715.aspx) on memory models suggests that this lazy initialization pattern is safe:

&lt;code&gt;
public class LazyInitClass { 
&#160;&#160;&#160;&#160;private static LazyInitClass myValue = null;

&#160;&#160;&#160;&#160;public static LazyInitClass GetValue() {
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;if (myValue == null)
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;myValue = new LazyInitClass();
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;return myValue;
&#160;&#160;&#160;&#160;}
};
&lt;/code&gt;

I find this particular example very tricky, even trickier than what Vance&#039;s article admits. I understand that the order of writes to myValue and myValue fields is guaranteed by the strong ordering of writes. But, the order of reads has to be enforced using some rule as well. My rough understanding is that x86/x64 will avoid reordering the reads because there is a data dependency between them.

Unfortunately, in this area, even experts disagree on what precisely is and what isn&#039;t guaranteed (&lt;a href=&quot;http://www.bluebytesoftware.com/blog/PermaLink,guid,3420c247-2da5-411b-8ce7-05082e1aba30.aspx&quot; rel=&quot;nofollow&quot;&gt;example&lt;/a&gt;), and so I am not going to claim to know. 

I hope this helps. The summary is this: publish the object either via a volatile field or a field protected by a lock, and you&#039;ll be fine. In typical cases, you&#039;ll have some sort of a synchronization between the reader and the writer to pass the object anyways, and that synchronization will be sufficient to insert the appropriate barriers.</description>
		<content:encoded><![CDATA[<p>Hi Matt,</p>
<p>The safe thing to do would be to publish the Test object by writing it into a volatile field.</p>
<p>1.    The writer first writes all fields on the Test object, and then writes the reference to the Test object into a volatile field.</p>
<p>2.    The reader first reads the reference from a volatile field, and then reads fields of the Test object.</p>
<p>If the object is published via a volatile field, the reader cannot possibly observe the state of the object before it was initialized by the constructor. An alternative solution is to write the object it into a regular field under a lock, and then read it under the same lock.</p>
<p>HOWEVER, in today&#8217;s .NET implementation on today&#8217;s hardware, I understand that you may be able to get away with removing the volatile modifier on the publication field, even though I would recommend against doing that. For example, Vance Morrison&#8217;s article (<a href="http://msdn.microsoft.com/en-us/magazine/cc163715.aspx" rel="nofollow">http://msdn.microsoft.com/en-u.....63715.aspx</a>) on memory models suggests that this lazy initialization pattern is safe:</p>
<p><code><br />
public class LazyInitClass {<br />
&nbsp;&nbsp;&nbsp;&nbsp;private static LazyInitClass myValue = null;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public static LazyInitClass GetValue() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (myValue == null)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;myValue = new LazyInitClass();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return myValue;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
};<br />
</code></p>
<p>I find this particular example very tricky, even trickier than what Vance&#8217;s article admits. I understand that the order of writes to myValue and myValue fields is guaranteed by the strong ordering of writes. But, the order of reads has to be enforced using some rule as well. My rough understanding is that x86/x64 will avoid reordering the reads because there is a data dependency between them.</p>
<p>Unfortunately, in this area, even experts disagree on what precisely is and what isn&#8217;t guaranteed (<a href="http://www.bluebytesoftware.com/blog/PermaLink,guid,3420c247-2da5-411b-8ce7-05082e1aba30.aspx" rel="nofollow">example</a>), and so I am not going to claim to know. </p>
<p>I hope this helps. The summary is this: publish the object either via a volatile field or a field protected by a lock, and you&#8217;ll be fine. In typical cases, you&#8217;ll have some sort of a synchronization between the reader and the writer to pass the object anyways, and that synchronization will be sufficient to insert the appropriate barriers.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Matt</title>
		<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/comment-page-1/#comment-1050</link>
		<dc:creator>Matt</dc:creator>
		<pubDate>Tue, 27 Jul 2010 01:42:01 +0000</pubDate>
		<guid isPermaLink="false">http://igoro.com/?p=468#comment-1050</guid>
		<description>Let&#039;s say we added a second field to your Test class &quot;private Object _loopLock = new Object();&quot; and used it to protect all reads and writes to _loop.  We know from the language spec that all fields are initialized to their default values (in this case null) (http://msdn.microsoft.com/en-us/library/aa645756%28v=VS.71%29.aspx).  As such, couldn&#039;t the &quot;set thread&quot; have a stale initial version of _loopLock in it&#039;s cache (i.e. &quot;null&quot;) and attempt to lock on it?  This seems to raise a chicken and egg problem of requiring a second lock to protect the first lock. And so on and so forth...</description>
		<content:encoded><![CDATA[<p>Let&#8217;s say we added a second field to your Test class &#8220;private Object _loopLock = new Object();&#8221; and used it to protect all reads and writes to _loop.  We know from the language spec that all fields are initialized to their default values (in this case null) (<a href="http://msdn.microsoft.com/en-us/library/aa645756%28v=VS.71%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-u.....71%29.aspx</a>).  As such, couldn&#8217;t the &#8220;set thread&#8221; have a stale initial version of _loopLock in it&#8217;s cache (i.e. &#8220;null&#8221;) and attempt to lock on it?  This seems to raise a chicken and egg problem of requiring a second lock to protect the first lock. And so on and so forth&#8230;</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Eyal-Shilony</title>
		<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/comment-page-1/#comment-1020</link>
		<dc:creator>Eyal-Shilony</dc:creator>
		<pubDate>Sat, 10 Jul 2010 02:41:41 +0000</pubDate>
		<guid isPermaLink="false">http://igoro.com/?p=468#comment-1020</guid>
		<description>Thank you for such a great explanation. :)</description>
		<content:encoded><![CDATA[<p>Thank you for such a great explanation. <img src='http://igoro.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Excellent C# Threading Memory Model Article &#187; JasonJackson.com</title>
		<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/comment-page-1/#comment-888</link>
		<dc:creator>Excellent C# Threading Memory Model Article &#187; JasonJackson.com</dc:creator>
		<pubDate>Wed, 28 Apr 2010 15:41:05 +0000</pubDate>
		<guid isPermaLink="false">http://igoro.com/?p=468#comment-888</guid>
		<description>[...] just read an excellent article on the memory model in .Net and C# as it relates to threading, written my Microsoft&#8217;s Igor [...]</description>
		<content:encoded><![CDATA[<p>[...] just read an excellent article on the memory model in .Net and C# as it relates to threading, written my Microsoft&#8217;s Igor [...]</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Chris Carrer</title>
		<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/comment-page-1/#comment-828</link>
		<dc:creator>Chris Carrer</dc:creator>
		<pubDate>Wed, 17 Mar 2010 22:53:14 +0000</pubDate>
		<guid isPermaLink="false">http://igoro.com/?p=468#comment-828</guid>
		<description>Igor:  Please disregard my comment - I was fighting with a threading bug all day and by the time I came upon this entry, my brain was working at 1/2 capacity.

Your explanation makes perfect sense.  My question was a case of classic overthinking the problem.

Glad I found this blog - it is so hard to find information about these subjects.  Following you on twitter now.

Thanks for the great writeup.</description>
		<content:encoded><![CDATA[<p>Igor:  Please disregard my comment &#8211; I was fighting with a threading bug all day and by the time I came upon this entry, my brain was working at 1/2 capacity.</p>
<p>Your explanation makes perfect sense.  My question was a case of classic overthinking the problem.</p>
<p>Glad I found this blog &#8211; it is so hard to find information about these subjects.  Following you on twitter now.</p>
<p>Thanks for the great writeup.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Igor Ostrovsky</title>
		<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/comment-page-1/#comment-827</link>
		<dc:creator>Igor Ostrovsky</dc:creator>
		<pubDate>Wed, 17 Mar 2010 22:01:35 +0000</pubDate>
		<guid isPermaLink="false">http://igoro.com/?p=468#comment-827</guid>
		<description>Chris: Can you give an example of the case you are concerned about?

Normally, thread-static fields should not have a problem.

A thread-static field has a separate copy of the value for each field. So, a thread cannot possibly see a value written by another thread, simply by design.

For example, if one thread is looping and polling a thread-static field, it is OK to hoist the read out of the loop. If another thread modifies the thread-static field, it will modify its own copy, not the one that the looping thread is checking.</description>
		<content:encoded><![CDATA[<p>Chris: Can you give an example of the case you are concerned about?</p>
<p>Normally, thread-static fields should not have a problem.</p>
<p>A thread-static field has a separate copy of the value for each field. So, a thread cannot possibly see a value written by another thread, simply by design.</p>
<p>For example, if one thread is looping and polling a thread-static field, it is OK to hoist the read out of the loop. If another thread modifies the thread-static field, it will modify its own copy, not the one that the looping thread is checking.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Chris Carrer</title>
		<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/comment-page-1/#comment-826</link>
		<dc:creator>Chris Carrer</dc:creator>
		<pubDate>Wed, 17 Mar 2010 21:42:22 +0000</pubDate>
		<guid isPermaLink="false">http://igoro.com/?p=468#comment-826</guid>
		<description>Great explanation!

I have a question I can&#039;t seem to get answered; what happens with respect to [ThreadStatic] variables?  It is my understanding that static variables marked with [ThreadStatic] could still suffer from the same mutlicore issues that volatile is meant to solve.</description>
		<content:encoded><![CDATA[<p>Great explanation!</p>
<p>I have a question I can&#8217;t seem to get answered; what happens with respect to [ThreadStatic] variables?  It is my understanding that static variables marked with [ThreadStatic] could still suffer from the same mutlicore issues that volatile is meant to solve.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Marc Gravell</title>
		<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/comment-page-1/#comment-819</link>
		<dc:creator>Marc Gravell</dc:creator>
		<pubDate>Fri, 12 Mar 2010 21:01:57 +0000</pubDate>
		<guid isPermaLink="false">http://igoro.com/?p=468#comment-819</guid>
		<description>This same point about &lt;code&gt;Monitor.Pulse&lt;/code&gt; was raised again (good timing!) here: http://stackoverflow.com/questions/2431238/

I think that demonstrates further that it is (at best) unclear. If any official word on this question &lt;i&gt;does&lt;/i&gt; surface, I&#039;d be &lt;b&gt;hugely&lt;/b&gt; interested.</description>
		<content:encoded><![CDATA[<p>This same point about <code>Monitor.Pulse</code> was raised again (good timing!) here: <a href="http://stackoverflow.com/questions/2431238/" rel="nofollow">http://stackoverflow.com/questions/2431238/</a></p>
<p>I think that demonstrates further that it is (at best) unclear. If any official word on this question <i>does</i> surface, I&#8217;d be <b>hugely</b> interested.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Igor Ostrovsky</title>
		<link>http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/comment-page-1/#comment-814</link>
		<dc:creator>Igor Ostrovsky</dc:creator>
		<pubDate>Mon, 08 Mar 2010 02:01:01 +0000</pubDate>
		<guid isPermaLink="false">http://igoro.com/?p=468#comment-814</guid>
		<description>@A R Karthick: Logically, the entire cache is flushed on each write. This is important for the &quot;safe publication&quot; pattern - you can initialize some data structure and write a reference to it into a volatile field. Any readers who see the reference to the data structure are guaranteed to see its contents in a fully initialized state. Admittedly, I don&#039;t fully understand all of the details in the hardware that make this guarantee happen.

@Massimiliano: I think that it is safe to assume that Monitor.Wait and Monitor.Pulse are full barriers. But, I cannot find it somewhere documented explicitly.</description>
		<content:encoded><![CDATA[<p>@A R Karthick: Logically, the entire cache is flushed on each write. This is important for the &#8220;safe publication&#8221; pattern &#8211; you can initialize some data structure and write a reference to it into a volatile field. Any readers who see the reference to the data structure are guaranteed to see its contents in a fully initialized state. Admittedly, I don&#8217;t fully understand all of the details in the hardware that make this guarantee happen.</p>
<p>@Massimiliano: I think that it is safe to assume that Monitor.Wait and Monitor.Pulse are full barriers. But, I cannot find it somewhere documented explicitly.</p>
]]></content:encoded>
	</item>
</channel>
</rss>
