<?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>Martijn's C# Programming Blog &#187; multi threading</title>
	<atom:link href="http://www.dijksterhuis.org/tag/multi-threading/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Creating and synchronizing Threads with C#</title>
		<link>http://www.dijksterhuis.org/creating-and-synchronizing-threads-with-c/</link>
		<comments>http://www.dijksterhuis.org/creating-and-synchronizing-threads-with-c/#comments</comments>
		<pubDate>Wed, 19 Nov 2008 06:59:37 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c-sharp]]></category>
		<category><![CDATA[multi threading]]></category>
		<category><![CDATA[Thread]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=182</guid>
		<description><![CDATA[
Multi-tasking / multi-threaded applications have always been a bit of a nightmare to create. Different operating systems and sometimes even different compilers and class libraries tends to have their own implementations. Fortunately the .NET /  C# implementation of threading is extremely straightforward and makes it simple to create a multi threaded application. In this [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/threads.jpg" alt="" title="Creating Threads with C#" width="500" height="274" class="alignnone size-full wp-image-186" /></p>
<p><em>Multi-tasking / multi-threaded applications have always been a bit of a nightmare to create. Different operating systems and sometimes even different compilers and class libraries tends to have their own implementations. Fortunately the .NET /  C# implementation of threading is extremely straightforward and makes it simple to create a multi threaded application. In this article we look at building some very simple threaded applications. We go into how to create them, synchronize them and how we can ensure that things such as shared variables are properly protected.</em></p>
<p><span id="more-182"></span></p>
<p>But what are threads anyway? Threading provides the ability for a program to split itself into smaller segments. For example, one thread takes care of the user interface while another task re-calculates data in the background. Because each thread has access to all the variables and memory of the running program there is a need to ensure that they play together nicely. This is solved by adding inter thread communication and synchronization.</p>
<p>To create a new thread, we need to include System.Threading which provides the Thread class. From there on creating a new thread involves only a few steps:</p>
<ol>
<li>Create a new instance of Thread   <em>[new Thread()]</em>
<li>Pass the code starting point point of the thread in its creation <em>[myThread = new Thread( new ThreadStart( myObj.EntryPoint ) )]</em>
<li>Start the Thread <em>[myThread.Start()]</em>
</ol>
<p>The <em>ThreadStart</em> object mentioned in the Thread constructor <a href="http://www.dijksterhuis.org/using-delegates-in-c/">is actually a delegate</a>. It defines the format that the entry point function should follow : a function returning &#8220;void&#8221; that takes no parameters. (Alternatively there is also <em>ParameterizedThreadStart</em> which allows you pass a parameter).</p>
<p>C# makes it possible to name every Thread Object and we use this to give a name to each of the Threads we create.</p>
<p>Each thread is then started and asked to print its name.  In total there will be three messages printed: by the main thread and the two threads we create in the example. Also notice that <i>Thread.CurrentThread</i> provides a reference to the currently executing thread.</p>
<pre class="brush: c#">
using System;
using System.Threading;

namespace TheadingDemo1
{

    class ThreadExample
    {

        static void ShowThreadName()
        {
            Console.WriteLine(&quot;Current Thread: {0}&quot;,Thread.CurrentThread.Name);
        }

        public void ThreadStartPoint()
        {
            ShowThreadName();
        }

        public static void Main()
        {
            // As we enter the program with this thread -- lets call it &quot;main&quot;
            Thread.CurrentThread.Name = &quot;Main&quot;;

            // Create two new instances of the current class
            ThreadExample instance1 = new ThreadExample();
            ThreadExample instance2 = new ThreadExample();

            // We need to setup their starting points, which is the same for both
            Thread thread1 = new Thread( new ThreadStart( instance1.ThreadStartPoint ));
            Thread thread2 = new Thread( new ThreadStart( instance2.ThreadStartPoint ));

            // Name each thread
            thread1.Name = &quot;Instance1&quot;;
            thread2.Name = &quot;Instance2&quot;;

            // Start both threads
            thread1.Start();
            thread2.Start();

            // Display the name of the current (main) thread
            ShowThreadName();           

            Console.WriteLine(&quot;Ending Main Tread&quot;);
        }

    }

}
</pre>
<p>The above example will print something similar to the following:</p>
<pre class="brush: c#">
Current Thread: Main
Current Thread: Instance2
Ending Main Tread
Current Thread: Instance1
</pre>
<p>Note that in this case Instance1 kept on running although the program had already ended. That is because C# makes a distinction between two different kinds of tasks: background tasks and foreground tasks. Foreground threads (the default) will keep the main thread from ending as long as there is still at least one other thread active. Background tasks  die when the programs main thread ends.</p>
<p>To see this effect , modify the above code by adding below line 35:</p>
<pre class="brush: c#">
thread1.IsBackground = true;
thread2.IsBackground = true;
</pre>
<p><strong>Many hands make light work</strong></p>
<p>In the above example we needed to create every task separately, but that becomes tedious if we need to create many. Using the <em>ThreadPool</em> class we only have to queue the actual work, which it will then allocate this to available tasks as required.</p>
<p>A simple example: we have a busy web server and as requests come in we need to serve them. But each request will probably take some time to complete as each thread will need to wait for disk IO and calculations to complete. The <em>ThreadPool</em> class will find an idle task for each new request and if it runs out of idle tasks the <em>ThreadPool</em> will simply create more threads.</p>
<p>Broken down in steps:</p>
<ol>
<li>We create 1000 instances of WebRequest
<li>Each is passed to the ReceiveRequest method
<li>The main thread starts waiting until everything has completed
<li>ReceiveRequest uses <em>ThreadPool.QueueUserWorkItem</em> to queue each request
<li>ThreadPool goes over each queue item, allocates it to a task which then calls &#8220;HandleRequest&#8221; for each
<li>The main thread is woken up
</ol>
<p>We do some more things to smooth communication but first have a look at the code example:</p>
<pre class="brush: c#">
namespace TheadingPool1
{
    // WebRequest
    //
    // This is a simple class that pretends to be a request received from the internet
    // Here it only need to carry a unique number so that we can identify it.

    class WebRequest
    {
        public int id;
        public WebRequest(int id)
        {
            this.id = id;
        }
    }

    // WebServer
    //
    // Our little webserver &quot;receives&quot; requests from the internet, and then queues them
    // The ThreadPool mechanism will allocate a new thread to

    class WebServer
    {
        public int QueueLength;
        ManualResetEvent WaitEvent;
        bool       WaitForComplete;

        public WebServer()
        {
            this.QueueLength = 0;
            this.WaitForComplete = false;
        }

        public void WaitForCompleted()
        {
            // We lock the class to ensure that nobody modifies the QueueLength
            // while we are inspecting it.
            lock(this)
            {
                if (this.QueueLength==0) return;
                WaitEvent = new ManualResetEvent(false);
                WaitForComplete = true;
            }
            // Outside the lock block as we need to free the lock!
            WaitEvent.WaitOne();
        }

        // ReceiveRequest
        //
        // Our webserver has received a request, we use the ThreadPool.QueueWorkItem
        // to find / create a thread that will handle this request.
        //
        // Actual handling of the request is done by the &quot;HandleRequest&quot; function

        public void ReceiveRequest(WebRequest req)
        {
            // This is very simple, there is no need to define the thread pool.
            // We just add work
            ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), req);
            this.QueueLength++;
        }

        public void HandleRequest(Object obj)
        {
            // Notes:
            //
            // 1. Thread.CurrentThread.GetHasCode provides a unique identifies for each thread
            // 2. We need to cast the generic object parameter to our web request

            Console.WriteLine(&quot;Thread {0} handles request {1}&quot;,
                              Thread.CurrentThread.GetHashCode(),
                              ((WebRequest) obj).id);

            // 3. We add sleep to simulate a task taking some time, otherwise its likely that
            //    a single task is able to handle all our requests in order.

            Thread.Sleep(100);

            // 4. Finished, we reduce one item from the queue. If the queue is empty we need
            //    to free the main program

            lock(this)
            {
                this.QueueLength--;
                if (this.QueueLength == 0 &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; this.WaitForComplete)
                {
                    this.WaitEvent.Set();
                }
            }
        }

        public static void Main()
        {
            WebServer server = new WebServer();

            // &quot;Receive&quot; 1000 requests from the internet and queue them
            for (int Lp = 0; Lp &lt; 1000; Lp ++)
                server.ReceiveRequest( new WebRequest( Lp ));

            // We wait until the queue has emptied
            server.WaitForCompleted();

            Console.WriteLine(&quot;Main Thread has completed&quot;);
        }
    }
}
</pre>
<p><strong>So how do we know if the work has been completed?</strong></p>
<p>The Webserver class keeps track of the number of outstanding tasks and as soon as this reaches zero the task completing the last work item frees the main task from its wait.</p>
<p>This is done by using a <em>ManualResetEvent</em>.</p>
<p>Any task which calls <em>WaitOne()</em> on a <em>ManualResetEvent</em> will be suspended until another task frees it by calling <em>Set()</em>. It is possible for more tasks to wait for the same <em>ManualResetEvent</em>, but in our example only the main task needs to wait.</p>
<p>When our <em>HandleRequest</em> method discovers that it has handled the last outstanding request it calls <em>Set()</em> freeing the main task to end the program.</p>
<p><strong>We need to avoid interruption</strong></p>
<p>As multiple tasks are executing the code at the same time several critical sections might be updated by more than one task at the same time.</p>
<p>In our example the critical code is the code which maintains the <em>QueueLength</em> variable. Every time a task is completed it reduces <em>QueueLength</em> by one, and every time a task is added <em>QueueLength</em> is increased. But what happens if a task reduces the <em>QueueLength</em> while another one is checking if its zero?</p>
<p>There are several things that could go unexpectedly wrong, which is something called a &#8220;race condition&#8221;.</p>
<p>We would like to ensure that these statements are executed in order and without interruption &#8212; as an essentially atomic operation.</p>
<p>C# allows you to synchronize tasks by exclusively locking a code segment with the lock() statement. Only one task can enter this segment of the code. All others tasks reaching it will be suspended until the first task has completed it.</p>
<pre class="brush: c#">
lock(this)
{
   // The code between these brackets can only be entered by one task modifying this instance
   // of the class
}
</pre>
<p>In the example above we have protected each critical section that modifies <em>QueueLength</em> by placing it in an exclusive block.</p>
<p>This is the ABC of building a threaded application in C#. In another article I hope to go further into the details of inter thread and inter process communication.</p>
<p><small>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/chefranden/">chefranden</a></small></p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/creating-and-synchronizing-threads-with-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
