<?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>Coffee, Code and Chocolate &#187; Multithreading</title>
	<atom:link href="http://blog.ganeshzone.net/blog/index.php/tag/multithreading/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.ganeshzone.net/blog</link>
	<description>throw new Exception(&#34;#fail&#34;);</description>
	<lastBuildDate>Mon, 26 Jul 2010 19:45:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Thread Synchronization techniques Part 2 &#8211; The ReaderWriterLock class</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/01/thread-synchronization-techniques-part-2-the-readerwriterlock-class/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/01/thread-synchronization-techniques-part-2-the-readerwriterlock-class/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 19:22:32 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Multithreading]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=754</guid>
		<description><![CDATA[<p style="text-align: justify;">In continuation to my earlier post about multithreading in .NET, I am writing about the ReaderWriterLock class which is one more method of thread synchronization.</p>
<p style="text-align: justify;">The ReaderWriterLock is based on the fact that the Monitor locking (lock keyword in C#) doesnt really make any distinction whether the thread accessing the variable is [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">In continuation to my earlier post about multithreading in .NET, I am writing about the ReaderWriterLock class which is one more method of thread synchronization.</p>
<p style="text-align: justify;">The ReaderWriterLock is based on the fact that the Monitor locking (lock keyword in C#) doesnt really make any distinction whether the thread accessing the variable is reading it or writing to it. If its only reading it, then we should not need an exclusive lock. So If we allow multiple threads to read the value, it would be much faster than having mutually exclusive locks, which means a more scalable application? On paper, yes &#8211; but not in reality.</p>
<p style="text-align: justify;">The problem with ReaderWriterLock is with its implementation. Several experts have slammed this technique and found that outside of limited scenarios, it is actually far slower than the <strong>Monitor.Enter</strong> method used to get an exclusive lock. ReaderWriterLock gives higher priority to reader threads then writers. This makes sense if you have many readers and only a few writers. So a lot of readers are able to read the resource while the writer has to wait longer to get the lock. But what If you have equal or more writers. The process of favoring readers make writer threads queued up and take a very long time to complete.</p>
<p style="text-align: justify;">Jeffrey Richter says that this performance loss is due to support for Recursion in the ReaderWriterLock class. Due to this, the class needs to maintain a record of the number of times each thread acquires the lock and increment and decrement the counter. When multiple reader threads acquire the same lock (remember ReaderWriterLock class allows simultaneous reads), a counter is maintained for each thread. This overhead is what causes the ReaderWriterLock to pale in comparison to the Monitor class. It is approximately 6 times slower.</p>
<p style="text-align: justify;">Here is a code sample. The Threads 1 and 3 are reader threads while the Thread 2 is a writer one. When you take a look at the output, its clear that the readers are granted simultaneous access to the _value variable, but when the writer thread is writing to it, all the readers wait in queue patiently for it to finish executing. I have made the DoWorkRead method parametrized in order to identify the thread on which the method is being executed.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">class</span> Program
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> _value <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
    ReaderWriterLock _rwLock <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ReaderWriterLock<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Program _prgm <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Program<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&amp;</span>lt<span style="color: #008000;">;</span> <span style="color: #FF0000;">20</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Thread _t1Obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span>_prgm.<span style="color: #0000FF;">DoWorkRead</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//Reader Thread</span>
            <span style="color: #008080; font-style: italic;">//Writer Thread</span>
            Thread _t2Obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ThreadStart<span style="color: #000000;">&#40;</span>_prgm.<span style="color: #0000FF;">DoWorkWrite</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Reader Again</span>
            Thread _t3Obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span>_prgm.<span style="color: #0000FF;">DoWorkRead</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> 
&nbsp;
            <span style="color: #008080; font-style: italic;">//Start all threads</span>
            _t1Obj.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread 1&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t2Obj.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t3Obj.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread 3&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//Wait for them to finish execution</span>
            _t1Obj.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t2Obj.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t3Obj.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWorkRead<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> threadName<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Accquire Reader Lock.</span>
        _rwLock.<span style="color: #0000FF;">AcquireReaderLock</span><span style="color: #000000;">&#40;</span>Timeout.<span style="color: #0000FF;">Infinite</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Read start: Thread: &quot;</span> <span style="color: #008000;">+</span> threadName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>threadName.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;Thread 1&quot;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #008080; font-style: italic;">//Irregular sleeps makes more chances of</span>
            <span style="color: #008080; font-style: italic;">//Multiple threads trying to access it</span>
            <span style="color: #008080; font-style: italic;">//at same time</span>
            Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">else</span>
            Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">250</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Read end  : Thread: &quot;</span> <span style="color: #008000;">+</span> threadName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _rwLock.<span style="color: #0000FF;">ReleaseReaderLock</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008080; font-style: italic;">//Release Lock</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWorkWrite<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _rwLock.<span style="color: #0000FF;">AcquireWriterLock</span><span style="color: #000000;">&#40;</span>Timeout.<span style="color: #0000FF;">Infinite</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\n</span>Writer start: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _value<span style="color: #008000;">++;</span> <span style="color: #008080; font-style: italic;">//Writing</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Writer End: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _rwLock.<span style="color: #0000FF;">ReleaseWriterLock</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p style="text-align: justify;">
<p style="text-align: justify;">A look at the output shows the once the writer acquires a lock, it is mutually exclusive, but both the reader threads are able to access the variable _value.</p>
<p style="text-align: justify;">
<p><a href="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/01/Output1.jpg"><img class="aligncenter size-full wp-image-787" title="Output" src="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/01/Output1.jpg" alt="" width="314" height="334" /></a></p>
<p style="text-align: justify;">
<p style="text-align: justify;">One more problem with the ReaderWriterLock class is that it allows Reader threads to acquire writer locks. If you set an infinite timeout, it will create a deadlock situation, where the thread just waits to get the Writer lock but cant because the very same thread holds on to the Reader lock and is yet to release it. So the application just waits and waits.</p>
<p style="text-align: justify;">

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWorkRead<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> threadName<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">//Accquire Reader Lock.</span>
            _rwLock.<span style="color: #0000FF;">AcquireReaderLock</span><span style="color: #000000;">&#40;</span>Timeout.<span style="color: #0000FF;">Infinite</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Read start: Thread: &quot;</span> <span style="color: #008000;">+</span> threadName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//NEVER EVER DO THE BELOW. IT WILL CREATE A DEADLOCK</span>
            _rwLock.<span style="color: #0000FF;">AcquireWriterLock</span><span style="color: #000000;">&#40;</span>Timeout.<span style="color: #0000FF;">Infinite</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Read start: Thread: &quot;</span> <span style="color: #008000;">+</span> threadName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _rwLock.<span style="color: #0000FF;">ReleaseReaderLock</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Release Lock</span>
        <span style="color: #000000;">&#125;</span></pre></div></div>

<p style="text-align: justify;">Keeping all these issues in mind, Microsoft introduced a new class &#8211; the ReaderWriterLockSlim class from .NET 3.0 onwards, while leaving the old one in there as well, for backwards compatibility. This class placed Lock recursion in the hands of the developers by giving an enum that could be set during object recursion. With recursion out of the way, performance is dramatically better and comparable to the Monitor class. It also took care of the deadlock situation above. As a conclusion, it is always better to avoid the ReaderWriterLock class and use the slim implementation instead. If you are on .NET 2.0, then since that option is not open to you, its better to look at some other synchronization technique.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/01/thread-synchronization-techniques-part-2-the-readerwriterlock-class/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Multithreading in .NET and Synchronization techniques &#8211; Part 1</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2009/12/multithreading-in-net-and-synchronization-techniques-part-1/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2009/12/multithreading-in-net-and-synchronization-techniques-part-1/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 20:20:18 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Multithreading]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=731</guid>
		<description><![CDATA[<p style="text-align: justify;">How often have you faced  the irritating not responding screen while the application waits for the data that you requested for. The problem is not with bad code or a slow database, the problem with conventional applications is that all the code is executed on a single thread. i.e. whenever an operation is [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">How often have you faced  the irritating not responding screen while the application waits for the data that you requested for. The problem is not with bad code or a slow database, the problem with conventional applications is that all the code is executed on a single thread. i.e. whenever an operation is performed the calling function must wait for it to complete in order to resume execution.</p>
<p style="text-align: justify;">Since the main thread is also the UI thread, the UI stops responding whenever its waiting for the function to return, making the user experience very bad. To avoid this, any time consuming operation should be executed on its own thread rather than the main thread. Lets see a simple example of a method created on another thread.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            ThreadingApp _testObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ThreadingApp<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//Declaring Two Objects for calling the parameterless and parametrized method</span>
            Thread _tObj1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ParameterizedThreadStart<span style="color: #000000;">&#40;</span>_testObj.<span style="color: #0000FF;">DoSomeWork</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Thread _tObj2 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ThreadStart<span style="color: #000000;">&#40;</span>_testObj.<span style="color: #0000FF;">DoWork</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//Calling the overloaded method</span>
            _tObj1.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;CustomParameter&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Calling the parameterless method</span>
            _tObj2.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #FF0000;">class</span> ThreadingApp<span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// Parameterless method executed on anothed</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWork<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Executed On another thread&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoSomeWork<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> _name<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Executed on another thread. Paramter: &quot;</span> <span style="color: #008000;">+</span> _name<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">The ability to pass parameters to methods on other threads is new in .NET 2.0. The delegate introduced for this is the <strong>ParametrizedThreadStart</strong> delegate which takes in an object parameter. Since its an object type, pretty much anything can be passed to the method. So creating new threads is pretty simple. But a word of caution here &#8211;  Threading unless used carefully can introduce very hard to detect bugs in your system.</p>
<p style="text-align: justify;">Multiple threads don&#8217;t cause any problem till the time each thread runs its own context not depending on shared resources or variables. The issues start when threads start to modify each others variables and access each others resources. Lets see a small example where multiple threads accessing the same variable can lead to unpredictable scenarios. In the below code two variables increment a class level variable and print the values before and after the incrementing. As you can see in the output below, it leads to a chaotic scenario where threads are misreading values and coming in each others way to access the variable.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> _value <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
        Program _prgm <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Program<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Thread _t1Obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ThreadStart<span style="color: #000000;">&#40;</span>_prgm.<span style="color: #0000FF;">DoWork1</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Thread _t2Obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ThreadStart<span style="color: #000000;">&#40;</span>_prgm.<span style="color: #0000FF;">DoWork2</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            _t1Obj.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t2Obj.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWork1<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread1 start: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _value<span style="color: #008000;">++;</span>
        <span style="color: #008080; font-style: italic;">//Introduced a small sleep to bring some entropy in the system</span>
        Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread1 End: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWork2<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread2 start: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _value<span style="color: #008000;">++;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread2 End: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">When we see the output, it looks pretty haphazard. Its easy to see the threads are confused about execution and misreading the value of the variable.</p>
<p><a href="http://blog.ganeshzone.net/blog/wp-content/uploads/2009/12/output.jpg"><img class="aligncenter size-full wp-image-739" title="output" src="http://blog.ganeshzone.net/blog/wp-content/uploads/2009/12/output.jpg" alt="" width="342" height="307" /></a></p>
<p style="text-align: justify;">The Monitor class can be used to synchronize threads in .NET. How it works is that it puts a lock on the currently executing code making all other threads wait before they can access the variables that current method has locked. The Monitor has two main static methods Monitor.Enter and Monitor.Exit for entering the lock and exiting from it. Apart from this there is also the Monitor.TryEnter which tries to gain ownership of the code block. If its not able to it returns false. This is very important since calling the Monitor.Exit for a block you dont have ownership of, would raise a <strong>SynchronizationLockException. </strong>However making sure to call Enter and Exit every time would get cumbersome for a developer and there are chances it might be forgotten. Here is where C# comes into rescue with the lock keyword. Enclosing the code within the lock block automatically does all the steps which are mentioned above.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">readonly</span> <span style="color: #FF0000;">object</span> _lockObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">object</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoWork1<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">lock</span> <span style="color: #000000;">&#40;</span>_lockObj<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread1 start: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _value<span style="color: #008000;">++;</span>
            <span style="color: #008080; font-style: italic;">//Introduced a small sleep to bring some entropy in the system</span>
            Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Thread1 End: &quot;</span> <span style="color: #008000;">+</span> _value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Enclosing the code within the lock block brings order back to the method execution and we can observe that that each thread waits for the other to complete before attempting to modify the variable. Here is the IL for the above method.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="cil" style="font-family:monospace;"><span style="color:maroon;font-weight:bold;">.method</span> <span style="color:blue;font-weight:bold;">public</span> <span style="color:blue;font-weight:bold;">hidebysig</span> <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span>  DoWork1<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span> <span style="color:blue;font-weight:bold;">cil</span> <span style="color:blue;font-weight:bold;">managed</span>
<span style="color: #006400;">&#123;</span>
&nbsp;
  IL_0000:  <span style="color:blue;">ldsfld</span>     <span style="color:purple;font-weight:bold;">object</span> ThreadingApp.Program::_lockObj
  IL_0005:  <span style="color:blue;">dup</span>
  IL_0007:  <span style="color:blue;">call</span>       <span style="color:purple;font-weight:bold;">void</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Threading.Monitor::<span style="color: #000033;">Enter</span><span style="color: #006400;">&#40;</span><span style="color:purple;font-weight:bold;">object</span><span style="color: #006400;">&#41;</span>
  <span style="color:maroon;font-weight:bold;">.try</span>
  <span style="color: #006400;">&#123;</span>
    <span style="color:gray;font-style:italic;">//Our method logic removed for brevity</span>
  <span style="color: #006400;">&#125;</span>  <span style="color:gray;font-style:italic;">// end .try</span>
  <span style="color:blue;font-weight:bold;">finally</span>
  <span style="color: #006400;">&#123;</span>
    IL_0057:  <span style="color:blue;">ldloc</span>.<span style="color:blue;">0</span>
    IL_0058:  <span style="color:blue;">call</span>       <span style="color:purple;font-weight:bold;">void</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Threading.Monitor::<span style="color: #000033;">Exit</span><span style="color: #006400;">&#40;</span><span style="color:purple;font-weight:bold;">object</span><span style="color: #006400;">&#41;</span>
    IL_005d:  <span style="color:blue;">endfinally</span>
  <span style="color: #006400;">&#125;</span>  <span style="color:gray;font-style:italic;">// end handler</span>
  IL_005e:  <span style="color:blue;">ret</span>
<span style="color: #006400;">&#125;</span> <span style="color:gray;font-style:italic;">// end of method Program::DoWork1</span></pre></td></tr></table></div>

<p>A very important point stressed time and again would be to make sure not to expose the locking object outside the class. If this is done, anyone can use the object to lock your methods and not release them while your application threads remain indefinitely waiting for the lock to be freed.</p>
<p>There are many other techniques for thread synchronization in .NET. I will be covering them in upcoming posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2009/12/multithreading-in-net-and-synchronization-techniques-part-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
