<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	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/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>sharpreflections.net &#187; Threading</title>
	<atom:link href="http://blog.sharpreflections.net/category/programming/threading/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.sharpreflections.net</link>
	<description>Thoughts about .Net, programming and other more important stuffs.</description>
	<lastBuildDate>Fri, 20 Nov 2009 00:24:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Simple parallel programming</title>
		<link>http://blog.sharpreflections.net/2009/05/18/simple-parallel-programming/</link>
		<comments>http://blog.sharpreflections.net/2009/05/18/simple-parallel-programming/#comments</comments>
		<pubDate>Mon, 18 May 2009 22:59:40 +0000</pubDate>
		<dc:creator>matteosp</dc:creator>
				<category><![CDATA[.Net Programming]]></category>
		<category><![CDATA[ParallelProgramming]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[.Net;Threading;ParallelProgramming]]></category>

		<guid isPermaLink="false">http://blog.sharpreflections.net/?p=105</guid>
		<description><![CDATA[While waiting for Parallel Extensions (wikipedia), that will be shipped with next .Net Framework release, I designed a couple of class that allow to quickly (and easily!) write code that make use of multi-threading and, therefore, speed-up many tasks. What I show here is a simple class able to collect pieces of code (in form [...]]]></description>
			<content:encoded><![CDATA[<p>While waiting for <a title="Parallel Programming with .NET" href="http://blogs.msdn.com/pfxteam" target="_blank">Parallel Extensions</a> (<a title="Parallel Extensions" href="http://en.wikipedia.org/wiki/Parallel_FX_Library" target="_blank">wikipedia</a>), that will be shipped with next .Net Framework release, I designed a couple of class that allow to quickly (and easily!) write code that make use of multi-threading and, therefore, speed-up many tasks. What I show here is a simple class able to collect pieces of code (in form of delegate) to be executed concurrently, and parallelize and synchronize the execution. The main goals I kept in mind while realizing the solution were:</p>
<ul>
<li>Ease of use, minimal requirement in terms of multi-threading skills</li>
<li>Allowing single-threaded code to be ported to multi-threading with few changes</li>
<li>Code readability</li>
<li>Support for exception management</li>
</ul>
<p>Here what I came up with:</p>
<p>The API exposes one class, <span class="csharpcode">ParallelExecutor</span>, and one interface, <span class="csharpcode">IExecutionResult</span> (plus a generic specialization of the interface and the necessary implementations). Before seeing the internals of the solution, I want to show <strong>the ease of use of the API</strong>.<br />
Let&#8217;s start with this example:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">void</span> SerialExecution()</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>    Uri uri; <span class="kwrd">int</span> <span class="kwrd">value</span>;</pre>
<pre><span class="lnum">   4:  </span></pre>
<pre class="alt"><span class="lnum">   5:  </span>    CallWebService(uri);</pre>
<pre><span class="lnum">   6:  </span>    PerformComputation(<span class="kwrd">value</span>);</pre>
<pre class="alt"><span class="lnum">   7:  </span>}</pre>
</div>
<p><span class="csharpcode">CallWebService()</span> and <span class="csharpcode">PerformComputation()</span> represent the most classic example of methods that can (and should!) run in parallel as they perform respectively I/O and CPU computation. But usually programmers haven&#8217;t enough confidence with multi-threading execution and synchronization to do things in the right way. In any case they shouldn&#8217;t care about this stuff, they should focus on coding logic, and not on coding about how the logic get&#8217;s executed. Let&#8217;s see how <span class="csharpcode">ParallelExecutor</span> comes in help:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">void</span> ParallelExecution</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>  Uri uri; <span class="kwrd">int</span> <span class="kwrd">value</span>;</pre>
<pre><span class="lnum">   4:  </span></pre>
<pre class="alt"><span class="lnum">   5:  </span>  ParallelExecutor executor = <span class="kwrd">new</span> ParallelExecutor();</pre>
<pre><span class="lnum">   6:  </span></pre>
<pre class="alt"><span class="lnum">   7:  </span>  executor.Add(CallWebService, uri);</pre>
<pre><span class="lnum">   8:  </span>  executor.Add(PerformComputation, <span class="kwrd">value</span>);</pre>
<pre class="alt"><span class="lnum">   9:  </span></pre>
<pre><span class="lnum">  10:  </span>  executor.WaitAll();</pre>
<pre class="alt"><span class="lnum">  11:  </span>}</pre>
</div>
<p>Not too bad, right? With a couple of lines I got the two methods run concurrently. This is pretty simple: the Add() method takes as arguments the method to invoke and the arguments of that method. The WaitAll() causes the calling thread to wait for all the methods passed to Add() to complete. Take a (partial) look to the <span class="csharpcode">ParallelExecutor</span> definition:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> ParallelExecutor</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>  <span class="kwrd">public</span> IExecutionInfo&lt;<span class="kwrd">object</span>&gt; Add(Action workItem)</pre>
<pre><span class="lnum">   4:  </span>  <span class="kwrd">public</span> IExecutionInfo&lt;<span class="kwrd">object</span>&gt; Add&lt;T&gt;(Action&lt;T&gt; workItem, T arg)</pre>
<pre class="alt"><span class="lnum">   5:  </span>  <span class="rem">//overloads for other Action versions </span></pre>
<pre><span class="lnum">   6:  </span></pre>
<pre class="alt"><span class="lnum">   7:  </span>  <span class="kwrd">public</span> IExecutionInfo&lt;TResult&gt; Add&lt;TResult&gt;(Func&lt;TResult&gt; workItem)</pre>
<pre><span class="lnum">   8:  </span>  <span class="kwrd">public</span> IExecutionInfo&lt;TResult&gt; Add&lt;T, TResult&gt;(Func&lt;T, TResult&gt; workItem, T arg)</pre>
<pre class="alt"><span class="lnum">   9:  </span>  <span class="rem">//overloads for other Func versions </span></pre>
<pre><span class="lnum">  10:  </span></pre>
<pre class="alt"><span class="lnum">  11:  </span>  <span class="kwrd">public</span> <span class="kwrd">bool</span> WaitAll():</pre>
<pre><span class="lnum">  12:  </span>}</pre>
</div>
<p>As you can see, method to be parallelized are passed to Add() in form of variations of Action and Func generics delegate (there are also overloads that take <span class="csharpcode">MethodInfo</span> and the standard <span class="csharpcode">Delegate</span>). But what about the Add() return type, <span class="csharpcode">IExecutionResult</span>? Let&#8217;s see the interface declaration:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">interface</span> IExecutionInfo</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>  <span class="kwrd">object</span>[] Args { get; }</pre>
<pre><span class="lnum">   4:  </span></pre>
<pre class="alt"><span class="lnum">   5:  </span>  Exception Exception { get; }</pre>
<pre><span class="lnum">   6:  </span></pre>
<pre class="alt"><span class="lnum">   7:  </span>  <span class="kwrd">object</span> Result { get; }</pre>
<pre><span class="lnum">   8:  </span>}</pre>
<pre class="alt"><span class="lnum">   9:  </span></pre>
<pre><span class="lnum">  10:  </span><span class="kwrd">public</span> <span class="kwrd">interface</span> IExecutionInfo&lt;TResult&gt; : IExecutionInfo</pre>
<pre class="alt"><span class="lnum">  11:  </span>{</pre>
<pre><span class="lnum">  12:  </span>  TResult Result { get; }</pre>
<pre class="alt"><span class="lnum">  13:  </span>}</pre>
</div>
<p>At every invocation of the Add() method an instance of a class implementing <span class="csharpcode">IExecutionResult</span> is created, and its Args property is filled with method invocation arguments. After the invocation completes, the Result and Exception property are filled too (in both case, if any). <strong>And the magic of generics allow the code to be type safe</strong>. So, returning to the example, if CallWebService() has a return value and if you want to check for exceptions, you can write:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">void</span> ParallelExecution</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>  Uri uri; <span class="kwrd">int</span> <span class="kwrd">value</span>;</pre>
<pre><span class="lnum">   4:  </span></pre>
<pre class="alt"><span class="lnum">   5:  </span>  ParallelExecutor executor = <span class="kwrd">new</span> ParallelExecutor();</pre>
<pre><span class="lnum">   6:  </span></pre>
<pre class="alt"><span class="lnum">   7:  </span>  IExecutionInfo&lt;<span class="kwrd">int</span>&gt; execution = executor.Add&lt;Uri, <span class="kwrd">int</span>&gt;(CallWebService, uri);</pre>
<pre><span class="lnum">   8:  </span>  executor.Add(PerformComputation, <span class="kwrd">value</span>);</pre>
<pre class="alt"><span class="lnum">   9:  </span></pre>
<pre><span class="lnum">  10:  </span>  executor.WaitAll();</pre>
<pre class="alt"><span class="lnum">  11:  </span></pre>
<pre><span class="lnum">  12:  </span>  <span class="kwrd">if</span> (execution.Exception != <span class="kwrd">null</span>)</pre>
<pre class="alt"><span class="lnum">  13:  </span>      ManageException(execution.Exception);</pre>
<pre><span class="lnum">  14:  </span>  <span class="kwrd">else</span></pre>
<pre class="alt"><span class="lnum">  15:  </span>      Console.WriteLine(<span class="str">"Result: {0}"</span>, execution.Result);</pre>
<pre><span class="lnum">  16:  </span>}</pre>
</div>
<p>Another couple of properties exposed by <span class="csharpcode">ParallelExecutor</span> allow you to control when the execution starts (immediately after Add() or when WaitAll() gets called) and the aggressiveness of the threading policy (one new Thread for every method passed to Add() or threads got from ThreadPool).</p>
<p>Obviously this is a very simple implementation, far away from what Parallel Extensions will be. But its simplicity may suite well some implementation with no heavy requirements.</p>
<p><a title="Simple parallel programming (MSDN Code Gallery)" href="http://code.msdn.microsoft.com/SimpleParallelExt" target="_blank">Source Code</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sharpreflections.net/2009/05/18/simple-parallel-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
