<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:copyright="http://blogs.law.harvard.edu/tech/rss" xmlns:image="http://purl.org/rss/1.0/modules/image/">
    <channel>
        <title>Concurrency</title>
        <link>http://geekswithblogs.net/jolson/category/8879.aspx</link>
        <description>Concurrency</description>
        <language>en-US</language>
        <copyright>Jason Olson</copyright>
        <managingEditor>jason@managed-world.com</managingEditor>
        <generator>Subtext Version 0.0.0.0</generator>
        <item>
            <title>Parallel Computing with Visual Studio 2010 Beta 1</title>
            <link>http://geekswithblogs.net/jolson/archive/2009/06/09/parallel-computing-with-visual-studio-2010-beta-1.aspx</link>
            <description>&lt;p&gt;One of the big areas of improvements coming to Visual Studio 2010 and .NET Framework 4 is in the area parallel computing. There are a LOT of new features and improvements to existing features here with this latest release of our developer tools. &lt;/p&gt;  &lt;p&gt;Many people smarter and more capable than I have already written about most of this stuff, so there’s not much for me to add. What I did want to do though is to let you know all the places where you can find this wealth of information (and there is a lot of it). So, without further ado, here is a list of content for you if you are interested in Parallel Computing with Visual Studio 2010 and .NET Framework 4 Beta 1.&lt;/p&gt;  &lt;p&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;MSDN&lt;/strong&gt;&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd460693(VS.100).aspx"&gt;Managed - Parallel Programming in the .NET Framework&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd504870(VS.100).aspx"&gt;Native – Concurrency Runtime&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd554943(VS.100).aspx"&gt;Walkthrough – Debugging a Parallel Application&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;strong&gt;What’s New…&lt;/strong&gt;&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/04/29/9576291.aspx"&gt;What’s New in Beta 1 for Parallel LINQ (PLINQ)&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/03/27/9514938.aspx"&gt;What’s New in Beta 1 for the Task Parallel Library (part 1/3)&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/04/06/9534426.aspx"&gt;What’s New in Beta 1 for the Task Parallel Library (part 2/3)&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/04/14/9549246.aspx"&gt;What’s New in Beta 1 for the Task Parallel Library (part 3/3)&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/03/04/9457880.aspx"&gt;What’s New in Beta 1 for the Coordination Data Structures&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/ericeil/archive/2009/04/23/clr-4-0-threadpool-improvements-part-1.aspx"&gt;CLR 4 ThreadPool Improvements (part 1)&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/05/22/9635790.aspx"&gt;.NET Framework 4 Cancellation Framework&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.danielmoth.com/Blog/2009/05/parallel-tasks-new-visual-studio-2010.html"&gt;Parallel Tasks – New Visual Studio 2010 Debugger Window&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.danielmoth.com/Blog/2009/05/parallel-stacks-another-new-vs2010.html"&gt;Parallel Stacks – Another New Visual Studio 2010 Debugger Window&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.danielmoth.com/Blog/2009/05/parallel-stacks-tasks-view.html"&gt;Parallel Stacks – Tasks View&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.danielmoth.com/Blog/2009/06/parallel-stacks-method-view.html"&gt;Parallel Stacks – Method View&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;strong&gt;Diving Deeper&lt;/strong&gt;&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/06/03/9691796.aspx"&gt;Mechanisms for Creating Tasks&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/06/02/9685804.aspx"&gt;The Nature of TaskCompletionSource&amp;lt;TResult&amp;gt;&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/05/31/9674669.aspx"&gt;Tasks and Unhandled Exceptions&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/06/09/9716439.aspx"&gt;Tasks and the APM Pattern&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/05/27/9645023.aspx"&gt;Exiting from Parallel Loops Early&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/06/06/9703059.aspx"&gt;Achieving Speedups with Small Parallel Loop Bodies&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/05/28/9648672.aspx"&gt;Partitioning in PLINQ&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;strong&gt;Channel 9 Videos&lt;/strong&gt;&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://channel9.msdn.com/shows/going+deep/erika-parsons-and-eric-eilebrecht--clr-4-inside-the-new-threadpool/"&gt;Erika Parsons and Eric Eilebrecht : CLR 4 - Inside the Thread Pool&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;strong&gt;More Oldie-But-Goodie Channel 9 Videos&lt;/strong&gt;&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://channel9.msdn.com/shows/Going+Deep/Concurrency-and-Parallelism-Native-CC-and-Managed-NET-Perspectives/"&gt;Concurrency and Parallelism: Native and Managed Perspectives&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://channel9.msdn.com/shows/Going+Deep/Joe-Duffy-Perspectives-on-Concurrent-Programming-and-Parallelism/"&gt;Joe Duffy: Perspectives on Concurrent Programming and Parallelism&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://channel9.msdn.com/shows/10-4/10-4-Episode-6-Parallel-Extensions/"&gt;10-4 Episode 6: Parallel Extensions&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;strong&gt;Misc…&lt;/strong&gt;&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://blogs.msdn.com/pfxteam/archive/2009/05/26/9641683.aspx"&gt;Known Issues in Parallel Extensions to .NET Framework 4 Beta 1&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/ParExtSamples"&gt;Samples for Parallel Programming with the .NET Framework 4&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Enjoy! There’s a lot here to digest. We definitely live in exciting times :).&lt;/p&gt;  &lt;p&gt;Do you know of some links that you like that I missed here? Feel free to let me know by adding a comment here.&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.pheedo.com/click.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=132721"&gt;&lt;img src="http://www.pheedo.com/img.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=132721" border="0"/&gt;&lt;/a&gt;&lt;/p&gt;&lt;iframe src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;PageID=31016&amp;amp;SiteID=1" width=1 height=1 Marginwidth=0 Marginheight=0 Hspace=0 Vspace=0 Frameborder=0 Scrolling=No&gt;
&lt;script language='javascript1.1' src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Browser=NETSCAPE4&amp;amp;NoCache=True&amp;PageID=31016&amp;amp;SiteID=1"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;a href="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Click&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" target="_blank"&gt;
&lt;img src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" width="1" height="1" border="0"  alt=""&gt;&lt;/a&gt;
&lt;/noscript&gt;
&lt;/iframe&gt;
&lt;img src="http://geekswithblogs.net/jolson/aggbug/132721.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Jason Olson</dc:creator>
            <guid>http://geekswithblogs.net/jolson/archive/2009/06/09/parallel-computing-with-visual-studio-2010-beta-1.aspx</guid>
            <pubDate>Wed, 10 Jun 2009 06:44:34 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/jolson/comments/132721.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/jolson/archive/2009/06/09/parallel-computing-with-visual-studio-2010-beta-1.aspx#feedback</comments>
            <slash:comments>6</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/jolson/comments/commentRss/132721.aspx</wfw:commentRss>
        </item>
        <item>
            <title>An Intro to Barrier, cont.d</title>
            <link>http://geekswithblogs.net/jolson/archive/2009/02/24/an-intro-to-barrier-cont.d.aspx</link>
            <description>&lt;p&gt;Well, I said I was going to be moving on to CountdownEvent, but I was wrong. there is one more aspect of using Barrier that I just had to share (thanks go to &lt;a href="http://blogs.msdn.com/toub/"&gt;Stephen Toub&lt;/a&gt; on the Parallel Computing Platform team for bringing this up). &lt;/p&gt;  &lt;p&gt;In &lt;a href="http://www.managed-world.com/archive/2009/02/09/an-intro-to-barrier.aspx"&gt;my first Barrier post&lt;/a&gt;, I had mentioned:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Barrier is a great new synchronization primitive to use when there is a known amount of work to do that is being done by different workers that all have common synchronization points.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;To make a long story short, this isn’t strictly true. Barrier can be used just fine when there is an unknown amount of work. The distinction between Barrier and other synchronization primitives isn’t about “known amount versus unknown amount of work”, it’s more about “usable once versus usable many times.” To explain this in more detail, let’s look back at the example from the last post (a Road Trip to Seattle). &lt;/p&gt;  &lt;h3&gt;Multiple Usages&lt;/h3&gt;  &lt;p&gt;First, it is perfectly allowed to use a Barrier more than once. Using the Road Trip metaphor, instead of going straight to Seattle after leaving the Gas Station, let’s have everybody stop for lunch on there way. So now there are two “sync points” that we have. First, we’ll wait for everybody to meet up at the gas station, then we’ll also wait for everybody to meet up for lunch after they’ve left the gas station. &lt;/p&gt;  &lt;p&gt;Revising our DriveToSeattle method from the last post, we will simply call SignalAndWait() a second time to provide a second sync point where everybody meets for lunch:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; DriveToSeattle(&lt;span class="kwrd"&gt;string&lt;/span&gt; name, TimeSpan timeDelay)
{
    &lt;span class="rem"&gt;// Perform some work&lt;/span&gt;
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Leaving House"&lt;/span&gt;, name);
    Thread.Sleep(timeDelay);
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Arrived at Gas Station"&lt;/span&gt;, name);

    &lt;span class="rem"&gt;// Need to wait for others&lt;/span&gt;
    sync.SignalAndWait();

    &lt;span class="rem"&gt;// Perform some work&lt;/span&gt;
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Leaving for Seattle"&lt;/span&gt;, name);
    Thread.Sleep(timeDelay);
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Meet for lunch"&lt;/span&gt;, name);

    &lt;span class="rem"&gt;// Need to wait for others&lt;/span&gt;
    sync.SignalAndWait();

    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Leaving for Seattle"&lt;/span&gt;, name);
}&lt;/pre&gt;
&lt;style type="text/css"&gt;&lt;![CDATA[
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }]]&gt;&lt;/style&gt;

&lt;p&gt;In real-word usage of the Barrier primitive, this doesn’t have to be limited to two uses of the Barrier. We can use the Barrier any number of times we need to in order to provide these common synchronization points for our parallel code. &lt;/p&gt;

&lt;h3&gt;Unknown Number of Workers&lt;/h3&gt;

&lt;p&gt;I mentioned that it wasn’t strictly true that Barrier is great for a just a known amount of work. That’s because Barrier provides the functionality you need to even use it when the number of workers performing our work is unknown. &lt;/p&gt;

&lt;p&gt;Back to our Road Trip. Dennis’s sister Dee is planning to come along on the Road Trip as well. However, she forgets to set her alarm and wakes up late. And unfortunately, Charlie, Mac, and Dennis have already left for Seattle. She still wants to go though so she plans to meet up with them for lunch. &lt;/p&gt;

&lt;p&gt;What we need is for a way for Dee to flag “Hey guys! I’m coming!” And it just so happens that the Barrier class provides an AddParticipant method that we can use to make sure the extra “worker” (Dee in this case) is included the next time everybody waits for each other to “complete their work.” &lt;/p&gt;

&lt;p&gt;In this case, Dee would simply “add herself” to the Barrier when her thread is spun up. To do this, let’s create a new DriveStraightToLunch method that will be used instead of the existing DriveToSeattle method we created before. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; DriveStraightToLunch(&lt;span class="kwrd"&gt;string&lt;/span&gt; name, TimeSpan timeDelay)
{
    &lt;span class="rem"&gt;// "I'm coming along guys"&lt;/span&gt;
    sync.AddParticipant();

    &lt;span class="rem"&gt;// Meet for lunch&lt;/span&gt;
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Leaving for Seattle"&lt;/span&gt;, name);
    Thread.Sleep(timeDelay);
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Meeting for lunch"&lt;/span&gt;, name);

    &lt;span class="rem"&gt;// Need to wait for others&lt;/span&gt;
    sync.SignalAndWait();

    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Leaving for Seattle"&lt;/span&gt;, name);
}&lt;/pre&gt;
&lt;style type="text/css"&gt;&lt;![CDATA[
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }]]&gt;&lt;/style&gt;

&lt;p&gt;And then we just spin up this new piece of work (added to our code in Main before all threads are joined):&lt;/p&gt;

&lt;pre class="csharpcode"&gt;... creation and start of Dennis thread

Thread.Sleep(TimeSpan.FromSeconds(6));
var dee = &lt;span class="kwrd"&gt;new&lt;/span&gt; Thread(() =&amp;gt; DriveStraightToLunch(&lt;span class="str"&gt;"Dee"&lt;/span&gt;, TimeSpan.FromSeconds(5)));
dee.Start();

dee.Join();
... join other threads&lt;/pre&gt;
&lt;style type="text/css"&gt;&lt;![CDATA[
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }]]&gt;&lt;/style&gt;

&lt;p&gt;It’s that simple.&lt;/p&gt;

&lt;h3&gt;In Closing&lt;/h3&gt;

&lt;p&gt;I hope in the last two posts you’ve seen how useful the new Barrier synchronization primitive can be when writing Parallel Code. API-wise there really isn’t much to the new Barrier class. Of course, as is usual with writing parallel code, it’s learning to use it correctly or use it in the right situations that’s the tricky part :). &lt;/p&gt;

&lt;p&gt;I would say "tune in next time when we chat about CountdownEvent” but considering this recent change of plans, I’m not going to tempt fate :). Later!&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.pheedo.com/click.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=129647"&gt;&lt;img src="http://www.pheedo.com/img.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=129647" border="0"/&gt;&lt;/a&gt;&lt;/p&gt;&lt;iframe src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;PageID=31016&amp;amp;SiteID=1" width=1 height=1 Marginwidth=0 Marginheight=0 Hspace=0 Vspace=0 Frameborder=0 Scrolling=No&gt;
&lt;script language='javascript1.1' src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Browser=NETSCAPE4&amp;amp;NoCache=True&amp;PageID=31016&amp;amp;SiteID=1"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;a href="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Click&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" target="_blank"&gt;
&lt;img src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" width="1" height="1" border="0"  alt=""&gt;&lt;/a&gt;
&lt;/noscript&gt;
&lt;/iframe&gt;
&lt;img src="http://geekswithblogs.net/jolson/aggbug/129647.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Jason Olson</dc:creator>
            <guid>http://geekswithblogs.net/jolson/archive/2009/02/24/an-intro-to-barrier-cont.d.aspx</guid>
            <pubDate>Tue, 24 Feb 2009 22:42:04 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/jolson/comments/129647.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/jolson/archive/2009/02/24/an-intro-to-barrier-cont.d.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/jolson/comments/commentRss/129647.aspx</wfw:commentRss>
        </item>
        <item>
            <title>An Intro to Barrier</title>
            <link>http://geekswithblogs.net/jolson/archive/2009/02/09/an-intro-to-barrier.aspx</link>
            <description>&lt;p&gt;In this first stage of our Tour de BCL, we will be passing through the new Barrier class. &lt;/p&gt;  &lt;p&gt;So what is a Barrier? Let’s take a look at the &lt;strike&gt;boring&lt;/strike&gt; technical description for a Barrier:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;A &lt;strong&gt;Barrier&lt;/strong&gt; is a synchronization primitive that enforces the stopping of execution between a number of threads or processes at a given point and prevents further execution until all threads or processors have reached the given point.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;I don’t know about you, but sometimes technical descriptions like the above just sound like “blah, blah, blah” to me. What does a Barrier really mean to me, as a developer. Let’s break it down a different way by looking at a specific real-life scenario.&lt;/p&gt;  &lt;h3&gt;Think of a Road Trip&lt;/h3&gt;  &lt;p&gt;Instead of looking at the technical description above, think of the concept of a road trip.&lt;/p&gt;  &lt;p&gt;There are three friends, Mac, Charlie, and Dennis. They live in a small town south of Seattle but want to take a road trip up to Seattle. So Mac calls up Charlie and Dennis and says “Hey guys, let’s take a road trip to Seattle. Meet up at the local gas station and then we’ll all leave from there.” So now they all now they need to go to the local gas station, wait for all of them to show up, and then they’ll leave for Seattle together and follow each other there. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://geekswithblogs.net/images/geekswithblogs_net/jolson/WindowsLiveWriter/AnIntroductiontoBarrier_D0FA/Barrier_4.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Barrier" border="0" alt="Barrier" src="http://geekswithblogs.net/images/geekswithblogs_net/jolson/WindowsLiveWriter/AnIntroductiontoBarrier_D0FA/Barrier_thumb_1.png" width="441" height="256" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Relating this scenario to some code, let’s say that Charlie, Mac, and Dennis are all individual threads that have one method of execution, the DriveToSeattle() method. Within that method, they are all going “to drive” to the same gas station and then continue to drive to Seattle.&lt;/p&gt;  &lt;p&gt;If we don’t use the Barrier to synchronize the work (aka wait for each other to arrive at the gas station), each one of them will leave for Seattle the second they arrive at the gas station: &lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    var charlie = &lt;span class="kwrd"&gt;new&lt;/span&gt; Thread(() =&amp;gt; {
        DriveToSeattle(&lt;span class="str"&gt;"Charlie"&lt;/span&gt;, TimeSpan.FromSeconds(1))
    }); 
    charlie.Start();

    var mac = &lt;span class="kwrd"&gt;new&lt;/span&gt; Thread(() =&amp;gt; {
        DriveToSeattle(&lt;span class="str"&gt;"Mac"&lt;/span&gt;, TimeSpan.FromSeconds(2))
    }); 
    mac.Start();

    var dennis = &lt;span class="kwrd"&gt;new&lt;/span&gt; Thread(() =&amp;gt; {
        DriveToSeattle(&lt;span class="str"&gt;"Dennis"&lt;/span&gt;, TimeSpan.FromSeconds(3))
    }); 
    dennis.Start();

    charlie.Join();
    mac.Join();
    dennis.Join();

    Console.ReadKey();
}

&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; DriveToSeattle(&lt;span class="kwrd"&gt;string&lt;/span&gt; name, TimeSpan timeToGasStation)
{
    &lt;span class="rem"&gt;// Drive to gas station&lt;/span&gt;
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Leaving House"&lt;/span&gt;, name);
    Thread.Sleep(timeToGasStation);
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Arrived at Gas Station"&lt;/span&gt;, name);

    &lt;span class="rem"&gt;// Need to sync here&lt;/span&gt;

    &lt;span class="rem"&gt;// Perform some more work&lt;/span&gt;
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Leaving for Seattle"&lt;/span&gt;, name);
}&lt;/pre&gt;
&lt;style type="text/css"&gt;&lt;![CDATA[


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }]]&gt;&lt;/style&gt;&lt;style type="text/css"&gt;&lt;![CDATA[


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }]]&gt;&lt;/style&gt;&lt;style type="text/css"&gt;&lt;![CDATA[


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }]]&gt;&lt;/style&gt;

&lt;p&gt;&lt;a href="http://geekswithblogs.net/images/geekswithblogs_net/jolson/WindowsLiveWriter/AnIntroductiontoBarrier_D0FA/BeforeBarrier_2.jpg"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="BeforeBarrier" border="0" alt="BeforeBarrier" src="http://geekswithblogs.net/images/geekswithblogs_net/jolson/WindowsLiveWriter/AnIntroductiontoBarrier_D0FA/BeforeBarrier_thumb.jpg" width="686" height="350" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Well, that’s hardly a road trip. If I were in Mac’s or Charlie’s shoes when Dennis left for Seattle without me, I know I would be a little upset. We obviously don’t want that to happen. So we can use the new Barrier to make sure they all “wait up” for each other at the gas station.&lt;/p&gt;

&lt;h3&gt;Using the new Barrier class&lt;/h3&gt;

&lt;p&gt;So how do you use the new Barrier class? It’s actually quite simple.The cool thing is that there are really only three things you need to learn to use the Barrier for this simple type of scenario: a single constructor and two method calls (both of which take zero parameters). Yes, it’s that simple to use.&lt;/p&gt;

&lt;p&gt;Let’s look at what our new code using Barrier looks like (the three bold lines are the new ones): &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;strong&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; Barrier sync;&lt;/strong&gt;

&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    &lt;strong&gt;sync = &lt;span class="kwrd"&gt;new&lt;/span&gt; Barrier(participantCount:3);&lt;/strong&gt;

    var charlie = &lt;span class="kwrd"&gt;new&lt;/span&gt; Thread(() =&amp;gt; {
        DriveToSeattle(&lt;span class="str"&gt;"Charlie"&lt;/span&gt;, TimeSpan.FromSeconds(1))
    }); 
    charlie.Start();

    var mac = &lt;span class="kwrd"&gt;new&lt;/span&gt; Thread(() =&amp;gt; {
        DriveToSeattle(&lt;span class="str"&gt;"Mac"&lt;/span&gt;, TimeSpan.FromSeconds(2))
    }); 
    mac.Start();

    var dennis = &lt;span class="kwrd"&gt;new&lt;/span&gt; Thread(() =&amp;gt; {
        DriveToSeattle(&lt;span class="str"&gt;"Dennis"&lt;/span&gt;, TimeSpan.FromSeconds(3))
    }); 
    dennis.Start();

    charlie.Join();
    mac.Join();
    dennis.Join();

    Console.ReadKey();
}

&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; DriveToSeattle(&lt;span class="kwrd"&gt;string&lt;/span&gt; name, TimeSpan timeToGasStation)
{
    &lt;span class="rem"&gt;// Drive to gas station&lt;/span&gt;
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Leaving House"&lt;/span&gt;, name);
    Thread.Sleep(timeToGasStation);
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Arrived at Gas Station"&lt;/span&gt;, name);

    &lt;span class="rem"&gt;// Need to sync here&lt;/span&gt;
    &lt;strong&gt;sync.SignalAndWait();&lt;/strong&gt;

    &lt;span class="rem"&gt;// Perform some more work&lt;/span&gt;
    Console.WriteLine(&lt;span class="str"&gt;"[{0}] Leaving for Seattle"&lt;/span&gt;, name);
}&lt;/pre&gt;
&lt;style type="text/css"&gt;&lt;![CDATA[


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }]]&gt;&lt;/style&gt;&lt;style type="text/css"&gt;&lt;![CDATA[


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }]]&gt;&lt;/style&gt;&lt;style type="text/css"&gt;&lt;![CDATA[


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }]]&gt;&lt;/style&gt;

&lt;p&gt;&lt;a href="http://geekswithblogs.net/images/geekswithblogs_net/jolson/WindowsLiveWriter/AnIntroductiontoBarrier_D0FA/AfterBarrier_2.jpg"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="AfterBarrier" border="0" alt="AfterBarrier" src="http://geekswithblogs.net/images/geekswithblogs_net/jolson/WindowsLiveWriter/AnIntroductiontoBarrier_D0FA/AfterBarrier_thumb.jpg" width="684" height="348" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;You can see now that nobody leaves for Seattle until everybody has arrived at the gas station. Essentially, with every call to SignalAndWait(), the number of signals received by the barrier is incremented. Once the number of signals received reaches the number of participants the Barrier was constructed with, all threads are then allowed to continue execution. And that’s all it takes to leverage the new Barrier class being introduced into the BCL with .NET Framework 4.0. &lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;But Jason&lt;/strong&gt;... What is up with that line of code: “sync = new Barrier(participantCount:3);”? I mean, what the heck is “participantCount:3”? How is that valid syntax?&lt;/p&gt;

  &lt;p&gt;Well, that’s easy. This is a new feature in C# 4.0 called Named Parameters where you can actually use a parameter’s name to specify what a value applies to. This becomes very handy in two places: 1) when combined with Optional Parameters, and 2) when used to clarify “magic numbers” (or “magic strings”, “magic booleans”, etc.) without having to introducing a temporary variable. &lt;/p&gt;

  &lt;p&gt;In this case, I could have left out participantCount and written just “sync = new Barrier(3);”. But I personally don’t like a magic number like “3” just floating around like this and Named Parameters give me an easy way to provide more context about the value “3”.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;In Closing&lt;/h3&gt;

&lt;p&gt;So let’s look back at that &lt;strike&gt;boring&lt;/strike&gt; technical description again:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;A &lt;strong&gt;Barrier&lt;/strong&gt; is a synchronization primitive that enforces the stopping of execution between a number of threads or processes at a given point and prevents further execution until all threads or processors have reached the given point.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Think about it this way:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;“stopping of execution between a number of threads...” = waiting for each other to arrive &lt;/li&gt;

  &lt;li&gt;“… at a given point” = the gas station &lt;/li&gt;

  &lt;li&gt;“prevents further execution until all threads… have reached the given point” = can’t leave for Seattle until everybody shows up &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;See? Nice and simple!&lt;/p&gt;

&lt;p&gt;Barrier is a great new synchronization primitive to use when there is a known amount of work to do that is being done by different workers that all have common synchronization points. However, if the amount of work needing to be done is not well known beforehand, Barrier is not the greatest primitive to use. Next we’ll look at another new synchronization primitive coming in .NET Framework 4.0 that is great to use when the amount of work is not known: the CountdownEvent. &lt;/p&gt;

&lt;p&gt;I hope you all enjoyed this first stage in our Tour de BCL. Until the next stage, we’ll see you later.&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.pheedo.com/click.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=129304"&gt;&lt;img src="http://www.pheedo.com/img.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=129304" border="0"/&gt;&lt;/a&gt;&lt;/p&gt;&lt;iframe src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;PageID=31016&amp;amp;SiteID=1" width=1 height=1 Marginwidth=0 Marginheight=0 Hspace=0 Vspace=0 Frameborder=0 Scrolling=No&gt;
&lt;script language='javascript1.1' src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Browser=NETSCAPE4&amp;amp;NoCache=True&amp;PageID=31016&amp;amp;SiteID=1"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;a href="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Click&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" target="_blank"&gt;
&lt;img src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" width="1" height="1" border="0"  alt=""&gt;&lt;/a&gt;
&lt;/noscript&gt;
&lt;/iframe&gt;
&lt;img src="http://geekswithblogs.net/jolson/aggbug/129304.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Jason Olson</dc:creator>
            <guid>http://geekswithblogs.net/jolson/archive/2009/02/09/an-intro-to-barrier.aspx</guid>
            <pubDate>Tue, 10 Feb 2009 11:17:39 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/jolson/comments/129304.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/jolson/archive/2009/02/09/an-intro-to-barrier.aspx#feedback</comments>
            <slash:comments>4</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/jolson/comments/commentRss/129304.aspx</wfw:commentRss>
        </item>
        <item>
            <title>Threading Basics: Race Conditions, Part 1</title>
            <link>http://geekswithblogs.net/jolson/archive/2008/09/18/threading-basics-race-conditions-part-1.aspx</link>
            <description>&lt;p&gt;I've talked in the past about the importance of parallel computing for all us developers. It's a trend in computer software and hardware architecture that is not a fad. Currently, in the US, it is nearly impossible to buy a new computer that has only a single core. We're even starting to see some of the first quad-core laptops hit the market. &lt;/p&gt;
&lt;p&gt;It's becoming very important for developers to start dealing with parallel code. There's one problem: multithreaded development is hard. And in the class of Threading 101, Race Conditions is one of the first chapters you have to deal with. &lt;/p&gt;
&lt;p&gt;So what is a &lt;strong&gt;Race Condition&lt;/strong&gt;? According to &lt;a href="http://en.wikipedia.org/wiki/Race_Conditions"&gt;Wikipedia&lt;/a&gt;, the source for all information on the Internet (emphasis mine):&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;"A race condition&lt;strong&gt;,&lt;/strong&gt; or race hazard, is a flaw in a system or process whereby the output and/or result of the process is unexpectedly and critically dependent on the sequence or timing of other events. The term originates with the idea of &lt;em&gt;&lt;strong&gt;two signals racing each other to influence the output first&lt;/strong&gt;&lt;/em&gt;."&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;That's nice and all, but what does this mean to us developers? Let's look at a simple example. I have a Logger where I want to keep track of the number of messages that are logged.&lt;/p&gt;
&lt;div style="BORDER-RIGHT: gray 1px solid; PADDING-RIGHT: 4px; BORDER-TOP: gray 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 8pt; PADDING-BOTTOM: 4px; MARGIN: 20px 0px 10px; OVERFLOW: auto; BORDER-LEFT: gray 1px solid; WIDTH: 97.5%; CURSOR: text; MAX-HEIGHT: 200px; LINE-HEIGHT: 12pt; PADDING-TOP: 4px; BORDER-BOTTOM: gray 1px solid; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BACKGROUND-COLOR: #f4f4f4"&gt;
&lt;div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   1:&lt;/span&gt; &lt;span style="COLOR: #0000ff"&gt;class&lt;/span&gt; Logger&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   2:&lt;/span&gt; {&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   3:&lt;/span&gt;     &lt;span style="COLOR: #0000ff"&gt;public&lt;/span&gt; &lt;span style="COLOR: #0000ff"&gt;static&lt;/span&gt; &lt;span style="COLOR: #0000ff"&gt;int&lt;/span&gt; TotalMessages = 0;&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   4:&lt;/span&gt;  &lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   5:&lt;/span&gt;     &lt;span style="COLOR: #0000ff"&gt;public&lt;/span&gt; &lt;span style="COLOR: #0000ff"&gt;void&lt;/span&gt; Log(&lt;span style="COLOR: #0000ff"&gt;string&lt;/span&gt; message)&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   6:&lt;/span&gt;     {&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   7:&lt;/span&gt;         &lt;span style="COLOR: #008000"&gt;// Do something with message&lt;/span&gt;&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   8:&lt;/span&gt;         TotalMessages++;&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   9:&lt;/span&gt;     }&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;  10:&lt;/span&gt; }&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Now let's call this method a bunch of times from four different threads and capture the total number of times Log message was called:&lt;/p&gt;
&lt;div style="BORDER-RIGHT: gray 1px solid; PADDING-RIGHT: 4px; BORDER-TOP: gray 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 8pt; PADDING-BOTTOM: 4px; MARGIN: 20px 0px 10px; OVERFLOW: auto; BORDER-LEFT: gray 1px solid; WIDTH: 97.5%; CURSOR: text; MAX-HEIGHT: 200px; LINE-HEIGHT: 12pt; PADDING-TOP: 4px; BORDER-BOTTOM: gray 1px solid; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BACKGROUND-COLOR: #f4f4f4"&gt;
&lt;div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   1:&lt;/span&gt; &lt;span style="COLOR: #0000ff"&gt;int&lt;/span&gt; messagesPerTask = 200000;&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   2:&lt;/span&gt; &lt;span style="COLOR: #0000ff"&gt;int&lt;/span&gt; unitsOfWork = 4;&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   3:&lt;/span&gt;  &lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   4:&lt;/span&gt; var logger = &lt;span style="COLOR: #0000ff"&gt;new&lt;/span&gt; Logger();&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   5:&lt;/span&gt; Parallel.For(0, unitsOfWork, (taskNumber) =&amp;gt;&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   6:&lt;/span&gt; {&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   7:&lt;/span&gt;     &lt;span style="COLOR: #0000ff"&gt;for&lt;/span&gt; (&lt;span style="COLOR: #0000ff"&gt;int&lt;/span&gt; i = 0; i &amp;lt; messagesPerTask; i++)&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   8:&lt;/span&gt;     {&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   9:&lt;/span&gt;         logger.Log(&lt;span style="COLOR: #006080"&gt;"Message "&lt;/span&gt; + i.ToString());&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;  10:&lt;/span&gt;     }&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;  11:&lt;/span&gt; });&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;  12:&lt;/span&gt;  &lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;  13:&lt;/span&gt; Console.WriteLine(&lt;span style="COLOR: #006080"&gt;"{0} Expected"&lt;/span&gt;, messagesPerTask * unitsOfWork);&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;  14:&lt;/span&gt; Console.WriteLine(&lt;span style="COLOR: #006080"&gt;"{0} Actual"&lt;/span&gt;, Logger.TotalMessages);&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;What do you expect the output to be? The obvious answer is "well, we are adding 200000 messages on four different threads, so it's obviously 800000". Unfortunately, the obvious answer also happens to be the wrong answer. What's the right answer? It depends, and it can change every single time you run the application. For example, this were the results from the first time I ran the code:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;800000 &lt;/strong&gt;Expected&lt;br /&gt;&lt;strong&gt;680354 &lt;/strong&gt;Actual&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Wait... how is this possible? Did we lose updates? Did I not call the method enough times? This surely must be a horrendous bug in the .NET Framework! Damn Bill and his blasted company. Trust me, it's not a bug. There's a good explanation of this behavior.&lt;/p&gt;
&lt;p&gt;If you haven't written a lot of multithreaded code yet, the problem with the above code may not be obvious. Truth be told, there really isn't a problem with the code... &lt;strong&gt;IF&lt;/strong&gt; you are only running the code on a single thread ever. But the likelihood of running on a single thread is becoming smaller and smaller. And as you can see, when we are running this in a multithreaded environment, there is most definitely a problem with the code.&lt;/p&gt;
&lt;p&gt;A lot of .NET developers look at "TotalMessages++" and interpret it as one line of code, one execution, one instruction, etc. But there's the rub, it isn't. The code "TotalMessages++" is actually &lt;strong&gt;four instructions&lt;/strong&gt; when compiled down to IL. &lt;/p&gt;
&lt;div style="BORDER-RIGHT: gray 1px solid; PADDING-RIGHT: 4px; BORDER-TOP: gray 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 8pt; PADDING-BOTTOM: 4px; MARGIN: 20px 0px 10px; OVERFLOW: auto; BORDER-LEFT: gray 1px solid; WIDTH: 97.5%; CURSOR: text; MAX-HEIGHT: 200px; LINE-HEIGHT: 12pt; PADDING-TOP: 4px; BORDER-BOTTOM: gray 1px solid; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BACKGROUND-COLOR: #f4f4f4"&gt;
&lt;div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   1:&lt;/span&gt; L_0001: ldsfld int32 CSharpSandbox.Logger::TotalMessages&lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   2:&lt;/span&gt; L_0006: ldc.i4.1 &lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: white; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   3:&lt;/span&gt; L_0007: add &lt;/pre&gt;&lt;pre style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 8pt; PADDING-BOTTOM: 0px; MARGIN: 0em; OVERFLOW: visible; WIDTH: 100%; COLOR: black; BORDER-TOP-STYLE: none; LINE-HEIGHT: 12pt; PADDING-TOP: 0px; FONT-FAMILY: consolas, 'Courier New', courier, monospace; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; BORDER-BOTTOM-STYLE: none"&gt;&lt;span style="COLOR: #606060"&gt;   4:&lt;/span&gt; L_0008: stsfld int32 CSharpSandbox.Logger::TotalMessages&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;These four lines essentially say the following:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Get the current value of TotalMessages 
&lt;/li&gt;&lt;li&gt;Get the value 1 
&lt;/li&gt;&lt;li&gt;Add the two numbers together 
&lt;/li&gt;&lt;li&gt;Save the result back into TotalMessages&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;Now let's imagine two threads executing the four steps above at the same time. Since threads won't be in perfect lock-step, they may be off by two steps (assuming the value of TotalMessages is currently 2):&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font color="#0000ce"&gt;[Thread 1] 1. Get the current value of TotalMessages (gets 2)&lt;br /&gt;[Thread 1] 2. Get the value 1&lt;/font&gt;&lt;br /&gt;&lt;font color="#00b900"&gt;[Thread 2] 1. Get the current value of TotalMessages (gets 2)&lt;br /&gt;[Thread 2] 2. Get the value 1&lt;/font&gt;&lt;br /&gt;&lt;font color="#0000c4"&gt;[Thread 1] 3. Add the two numbers together (2 + 1)&lt;br /&gt;[Thread 1] 4. Save the result back into TotalMessages (saves 3)&lt;/font&gt;&lt;br /&gt;&lt;font color="#009100"&gt;[Thread 2] 3. Add the two numbers together (2 + 1)&lt;br /&gt;[Thread 2] 4. Save the result back into TotalMessages (saves 3)&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;So we've executed that code twice and at the end of the execution, TotalMessages has only increased by one. This is exactly what a race condition is. It's that simple. It's not as advanced as a concept as one might think.&lt;/p&gt;
&lt;p&gt;This is why developers need to understand what race conditions are. A snippet of code that looks completely innocuous can cause some big problems when run in a multithreaded development. While future technologies will make writing parallel code easier, it won't prevent these types of problems from occurring. You still need to be aware of some of the common Threading 101 concerns/topics that exist today.&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.pheedo.com/click.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=126156"&gt;&lt;img src="http://www.pheedo.com/img.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=126156" border="0"/&gt;&lt;/a&gt;&lt;/p&gt;&lt;iframe src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;PageID=31016&amp;amp;SiteID=1" width=1 height=1 Marginwidth=0 Marginheight=0 Hspace=0 Vspace=0 Frameborder=0 Scrolling=No&gt;
&lt;script language='javascript1.1' src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Browser=NETSCAPE4&amp;amp;NoCache=True&amp;PageID=31016&amp;amp;SiteID=1"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;a href="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Click&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" target="_blank"&gt;
&lt;img src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" width="1" height="1" border="0"  alt=""&gt;&lt;/a&gt;
&lt;/noscript&gt;
&lt;/iframe&gt;
&lt;img src="http://geekswithblogs.net/jolson/aggbug/126156.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Jason Olson</dc:creator>
            <guid>http://geekswithblogs.net/jolson/archive/2008/09/18/threading-basics-race-conditions-part-1.aspx</guid>
            <pubDate>Fri, 19 Sep 2008 08:13:42 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/jolson/comments/126156.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/jolson/archive/2008/09/18/threading-basics-race-conditions-part-1.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/jolson/comments/commentRss/126156.aspx</wfw:commentRss>
        </item>
        <item>
            <title>True CCR Concurrency - Using CCR without Iterators</title>
            <link>http://geekswithblogs.net/jolson/archive/2008/06/21/true-ccr-concurrency---using-ccr-without-iterators.aspx</link>
            <description>&lt;p&gt;As developers get up to speed with the CCR, they quickly come across the (ab)use of iterators to achieve "concurrency." Okay, "(ab)use" may have been a bit of a low-blow. I call it an abuse as it is a totally unorthodox use of what iterators are usually used for, and I've came across my fair share of developers who find this unorthodox usage highly confusing. Not only is it confusing, but it's not what I would consider true concurrent code. &lt;/p&gt; &lt;p&gt;In a concurrent environment, if I create twenty different tasks that need to be executed, I expect several of those tasks to be executed at the exact same time (depending on the number of processors I have on my system). As a side effect of this concurrent execution of tasks, the order in which those tasks are executed is not guaranteed. If you don't have several tasks executing concurrently, and order of processing is indeed guaranteed, that's about as close you can get to being normal sequential code.&lt;/p&gt; &lt;p&gt;Look at &lt;a href="http://msdn.microsoft.com/en-us/library/bb648753.aspx"&gt;this sample&lt;/a&gt; (example 18) from MSDN. If you execute and step through this code, you will find that the method actually executes sequentially. The code posts a number, processes the number, posts another number, processes that number, etc. This is highly sequential. One could argue this is simply not the best sample for CCR iterators. However, after using CCR when developing robots using Robotics Studio, you will find that this "sequential but not" pattern is a very frequent pattern that is used when using CCR iterators. &lt;/p&gt; &lt;p&gt;There's also the impact of having a method that essentially never exits due to the "while (true)" nature of the iterator-based method that is determining what tasks need to execute (leading to a highly coupled, monolithic application). This doesn't mean that the CCR itself isn't useful though. You just need to know how to leverage the framework while avoiding some of these "rough spots".&lt;/p&gt; &lt;p&gt;So let's take a look at an example of how to use CCR to achieve "true" concurrency with the CCR without the use of iterators (for you VB fans, the great part of this approach is that it is entirely possible with VB like I show here). &lt;/p&gt; &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:ca039178-4dc5-47a9-84b6-be6dfa1399be" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="vb:nocontrols"&gt;Dim myPort As New Port(Of Integer)&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;At the heart of the message-based infrastructure in the CCR is a Port. A Port is where messages are posted to, and pulled from when tasks are actually executed. As seen above, Ports are strongly typed through the use of generics, and so they support posting/pulling of largely any POCO (Plain Ole CLR Object) you wish. In the case of this very simple demo we just use integers, but in a real system this might be self-defined types like StockQuoteRequestMessage, FoodOrderMessage, etc. &lt;/p&gt;
&lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:212852ab-3778-4d24-82f8-5db494faa6db" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="vb:nocontrols:firstline[3]"&gt;    Sub Main()
        Dim taskDispatcher As New Dispatcher(4, "Sample Dispatcher")
        Dim taskQueue As New DispatcherQueue("Sample Tasks", taskDispatcher)
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In the CCR, a DispatcherQueue contains a list of tasks to be executed, while a Dispatcher controls the execution of those tasks. Here we force our dispatcher to run four tasks concurrently even if we are on a single processor machine just so we can see the concurrency in action. Then we simply pass our dispatcher to the queue that contains the tasks that will be managed.&lt;/p&gt;
&lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:f5abd4d2-5220-4886-b623-d4a1e9953dd4" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="vb:nocontrols:firstline[7]"&gt;        ' Create the task that will handle our work
        Dim workReceiver = Arbiter.Receive(Of Integer)(True, _
                                myPort, _
                                Function(i) ProcessValue(i))

        ' Register the task with the CCR task queue
        Arbiter.Activate(taskQueue, workReceiver)

        ' Post some work to do
        For i = 0 To 9
            myPort.Post(i)
        Next
&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;When we create our workReceiver, we are essentially telling the CCR that we want a persistent task (one that will last across the processing lifetime of many messages, possibly until the application exits), and that when a message comes in on our Port, we will process that message with our function ProcessValue (defined below). Once the receiver is created, we simply hook it up to the task queue, and we're off to the races. &lt;/p&gt;
&lt;p&gt;Finally, all we need to do is wait until all values have been processed and exit the application.&lt;/p&gt;
&lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:3d9ba87e-f34f-4269-a75f-d61fea2ea305" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="vb:nocontrols:firstline[20]"&gt;        ' Wait until all tasks are finished
        While myPort.ItemCount &amp;gt; 0
            Thread.Sleep(TimeSpan.FromMilliseconds(200))
        End While

        taskQueue.Dispose()
        taskDispatcher.Dispose()

        Console.Write("Press any key to exit...")
        Console.ReadKey(True)
    End Sub&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;So when a message is posted to our port, CCR will call our function ProcessValue in order to process the message (as specified when we created the task to process messages). In our process function, we are simply going to write to the console at the beginning and at the end as well as sleeping our thread in the middle to simulate some work being done in the function.&lt;/p&gt;
&lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:baee8e13-2048-472e-8eee-e92084b0f8ee" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="vb:nocontrols:firstline[32]"&gt;    Function ProcessValue(ByVal value As Integer)

        Console.WriteLine("Begin " + value.ToString())
        Thread.Sleep(TimeSpan.FromMilliseconds(200))
        Console.WriteLine("End " + value.ToString())

        Return Nothing
    End Function&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;When I actually execute this sample, you can see the parallel nature of the execution by viewing the output (your output may differ as it can differ upon every execution thanks to the non-deterministic nature of concurrency):&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Begin 0&lt;br /&gt;Begin 1&lt;br /&gt;Begin 3&lt;br /&gt;Begin 2&lt;br /&gt;End 2&lt;br /&gt;Begin 4&lt;br /&gt;End 1&lt;br /&gt;Begin 5&lt;br /&gt;End 0&lt;br /&gt;Begin 6&lt;br /&gt;End 3&lt;br /&gt;Begin 7&lt;br /&gt;End 4&lt;br /&gt;Begin 8&lt;br /&gt;End 5&lt;br /&gt;End 6&lt;br /&gt;Begin 9&lt;br /&gt;End 7&lt;br /&gt;End 8&lt;br /&gt;End 9&lt;br /&gt;Press any key to exit...&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;  &lt;/p&gt;&lt;p&gt;And that's all we need to do in order to use CCR to process incoming messages in parallel (and in a "true" concurrent fashion). Just as a recap, here's the entire sample in one place:&lt;/p&gt;
&lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:1e64e149-1c7d-40c6-96b5-2843be231d10" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="vb:nocontrols"&gt;
    Dim myPort As New Port(Of Integer)

    Sub Main()
        Dim taskDispatcher As New Dispatcher(4, "Sample Dispatcher")
        Dim taskQueue As New DispatcherQueue("Sample Tasks", taskDispatcher)

        ' Create the task that will handle our work
        Dim workReceiver = Arbiter.Receive(Of Integer)(True, _
                                myPort, _
                                Function(i) ProcessValue(i))

        ' Register the task with the CCR task queue
        Arbiter.Activate(taskQueue, workReceiver)

        ' Post some work to do
        For i = 0 To 9
            myPort.Post(i)
        Next

        ' Wait until all tasks are finished
        While myPort.ItemCount &amp;gt; 0
            Thread.Sleep(TimeSpan.FromMilliseconds(200))
        End While

        taskQueue.Dispose()
        taskDispatcher.Dispose()

        Console.Write("Press any key to exit...")
        Console.ReadKey(True)
    End Sub

    Function ProcessValue(ByVal value As Integer)

        Console.WriteLine("Begin " + value.ToString())
        Thread.Sleep(TimeSpan.FromMilliseconds(200))
        Console.WriteLine("End " + value.ToString())

        Return Nothing
    End Function&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;As a "hello world" sample for using the CCR, this is a very simple demo. But it shows that it is very easy to actually achieve concurrent applications with the CCR without having to use CCR iterators. At the same time, avoiding the use of CCR iterators enable us to write a message-oriented application that can be properly modularized by "separating concerns" into independent message processors through the use of Ports. &lt;/p&gt;
&lt;p&gt;Of course, an added benefit of taking a "non-iterator" approach when using the CCR is that languages that don't have direct support for iterators (like VB.NET) can also develop CCR-based applications to achieve highly-parallel solutions.&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.pheedo.com/click.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=126159"&gt;&lt;img src="http://www.pheedo.com/img.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=126159" border="0"/&gt;&lt;/a&gt;&lt;/p&gt;&lt;iframe src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;PageID=31016&amp;amp;SiteID=1" width=1 height=1 Marginwidth=0 Marginheight=0 Hspace=0 Vspace=0 Frameborder=0 Scrolling=No&gt;
&lt;script language='javascript1.1' src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Browser=NETSCAPE4&amp;amp;NoCache=True&amp;PageID=31016&amp;amp;SiteID=1"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;a href="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Click&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" target="_blank"&gt;
&lt;img src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" width="1" height="1" border="0"  alt=""&gt;&lt;/a&gt;
&lt;/noscript&gt;
&lt;/iframe&gt;
&lt;img src="http://geekswithblogs.net/jolson/aggbug/126159.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Jason Olson</dc:creator>
            <guid>http://geekswithblogs.net/jolson/archive/2008/06/21/true-ccr-concurrency---using-ccr-without-iterators.aspx</guid>
            <pubDate>Sat, 21 Jun 2008 19:22:40 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/jolson/comments/126159.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/jolson/archive/2008/06/21/true-ccr-concurrency---using-ccr-without-iterators.aspx#feedback</comments>
            <slash:comments>3</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/jolson/comments/commentRss/126159.aspx</wfw:commentRss>
        </item>
        <item>
            <title>Parallel Extensions to the .NET Framework, June 2008 CTP Released!</title>
            <link>http://geekswithblogs.net/jolson/archive/2008/06/02/parallel-extensions-to-the-.net-framework-june-2008-ctp-released.aspx</link>
            <description>&lt;p&gt;The latest CTP for Parallel Extensions to the .NET Framework was released out to the intarw3bs today (Go &lt;a href="http://digg.com/programming/New_Parallel_Extensions_to_the_NET_Framework_CTP_Released_2"&gt;Digg It on Digg&lt;/a&gt; and &lt;a href="http://www.dotnetkicks.com/csharp/New_Parallel_Extensions_to_the_NET_Framework_CTP_Released"&gt;Kick It on DotNetKicks&lt;/a&gt;). This is the second major CTP for the Parallel Extensions.&lt;/p&gt; &lt;p&gt;If you're the kind of person who likes to just get the latest install and play around, you can &lt;a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&amp;amp;displaylang=en"&gt;find it here&lt;/a&gt;. If, however, you are a person who would like to read some resources about the new CTP first, there's a bunch of links for you as well:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Ed Essey &lt;a href="http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567802.aspx"&gt;announces the release&lt;/a&gt; on the &lt;a href="http://blogs.msdn.com/pfxteam/default.aspx"&gt;Parallel Extensions Team Blog&lt;/a&gt;&lt;/li&gt; &lt;li&gt;Ed outlines the &lt;a href="http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567093.aspx"&gt;new features in this CTP&lt;/a&gt;&lt;/li&gt; &lt;li&gt;Ed talks about the &lt;a href="http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567816.aspx"&gt;known issues with this CTP&lt;/a&gt;&lt;/li&gt; &lt;li&gt;Joe &lt;a href="http://www.bluebytesoftware.com/blog/2008/06/02/NewCTPOfParallelExtensionsIsAvailable.aspx"&gt;discusses the new release&lt;/a&gt;&lt;/li&gt; &lt;li&gt;Ed on &lt;a href="http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567825.aspx"&gt;why feedback is important&lt;/a&gt; to the team&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Here are some of the reactions (or re-announcements) from other bloggers:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://www.damonpayne.com/2008/06/02/June2008ParallelExtensionsCTP.aspx"&gt;Damon Payne&lt;/a&gt; on the release&lt;/li&gt; &lt;li&gt;&lt;a href="http://blogs.microsoft.co.il/blogs/tamir/archive/2008/06/02/just-released-parallel-extensions-june-ctp.aspx"&gt;Tamir Khason&lt;/a&gt; on the release&lt;/li&gt; &lt;li&gt;&lt;a href="http://blogs.msdn.com/bspann/archive/2008/06/02/parallel-extensions-june-2008-ctp.aspx"&gt;Brian Spann&lt;/a&gt; on the release&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;I think a very important quote from Joe is (emphasis mine):&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;em&gt;"I'm really excited to see our entire stack finally shipping &lt;strong&gt;as one cohesive unit&lt;/strong&gt;: the &lt;strong&gt;data structures we use throughout the implementation exposed publicly &lt;/strong&gt;(what we now call CDS), a &lt;strong&gt;new scheduler&lt;/strong&gt; built from the ground up, &lt;strong&gt;TPL and PLINQ better together&lt;/strong&gt;, and lots more."&lt;/em&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;I find this release very exciting, especially the "cohesive unit" part. As Ed mentions in the &lt;a href="http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567093.aspx"&gt;new features post&lt;/a&gt;, PLINQ is now running directly on top of TPL, rather than using the ThreadPool like it did before. The data structures used internally are now exposed as CDS. TPL with many improvements to the scheduler. This is a very great CTP for the Parallel Extensions Team. So congratulations to the team!&lt;/p&gt; &lt;p&gt;If you want to play around with concurrent programming in .NET, Parallel Extensions to the .NET Framework is the place to be. The team really wants your feedback and, through this feedback, you can help shape the future of concurrent programming in .NET. How exciting is that?!? So go grab the bits, install them, and enjoy!&lt;/p&gt; &lt;p&gt;And if you're a Parallel Extensions fan, be sure to &lt;a href="http://digg.com/programming/New_Parallel_Extensions_to_the_NET_Framework_CTP_Released_2"&gt;Digg It&lt;/a&gt; and &lt;a href="http://www.dotnetkicks.com/csharp/New_Parallel_Extensions_to_the_NET_Framework_CTP_Released"&gt;Kick It&lt;/a&gt;!&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.pheedo.com/click.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=126166"&gt;&lt;img src="http://www.pheedo.com/img.phdo?x=6cda6ad746d942b9a1110d0715a4fa12&amp;u=126166" border="0"/&gt;&lt;/a&gt;&lt;/p&gt;&lt;iframe src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;PageID=31016&amp;amp;SiteID=1" width=1 height=1 Marginwidth=0 Marginheight=0 Hspace=0 Vspace=0 Frameborder=0 Scrolling=No&gt;
&lt;script language='javascript1.1' src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Browser=NETSCAPE4&amp;amp;NoCache=True&amp;PageID=31016&amp;amp;SiteID=1"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;a href="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Click&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" target="_blank"&gt;
&lt;img src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&amp;amp;Task=Get&amp;amp;Mode=HTML&amp;amp;SiteID=1&amp;amp;PageID=31016" width="1" height="1" border="0"  alt=""&gt;&lt;/a&gt;
&lt;/noscript&gt;
&lt;/iframe&gt;
&lt;img src="http://geekswithblogs.net/jolson/aggbug/126166.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Jason Olson</dc:creator>
            <guid>http://geekswithblogs.net/jolson/archive/2008/06/02/parallel-extensions-to-the-.net-framework-june-2008-ctp-released.aspx</guid>
            <pubDate>Tue, 03 Jun 2008 08:01:41 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/jolson/comments/126166.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/jolson/archive/2008/06/02/parallel-extensions-to-the-.net-framework-june-2008-ctp-released.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/jolson/comments/commentRss/126166.aspx</wfw:commentRss>
        </item>
    </channel>
</rss>