<?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>gothi &#187; Threading</title>
	<atom:link href="http://www.gothi.co.uk/tag/threading/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gothi.co.uk</link>
	<description>A badly chosen byte</description>
	<lastBuildDate>Thu, 26 Jan 2012 22:34:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using Critical Sections with Delphi</title>
		<link>http://www.gothi.co.uk/2006/10/using-critical-sections-with-delphi/</link>
		<comments>http://www.gothi.co.uk/2006/10/using-critical-sections-with-delphi/#comments</comments>
		<pubDate>Sat, 21 Oct 2006 13:53:00 +0000</pubDate>
		<dc:creator>gothi</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[TCriticalSection]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://gothi.co.uk/using-critical-sections-with-delphi/</guid>
		<description><![CDATA[Delphi makes threading a very easy process, I&#8217;ve used it on numerous projects however there&#8217;s always room to learn new tricks. When multiple threads want to access the same shared data you have to lock it to avoid complications, in my projects I use a TCriticalSection.The Delphi docs and even my Mastering Delphi book were [...]]]></description>
			<content:encoded><![CDATA[<p>Delphi makes threading a very easy process, I&#8217;ve used it on numerous projects however there&#8217;s always room to learn new tricks.</p>
<p>When multiple threads want to access the same shared data you have to lock it to avoid complications, in my projects I use a TCriticalSection.<br />The Delphi docs and even my Mastering Delphi book were very vague on the use of this and so I&#8217;m hoping that this post will help others avoid the pitfall of misuse I did:</p>
<p>I assumed that I could use a Critical Section like so:</p>
<p><font color="Green">//vars, I use them as part of a class</font><br />var<br />cs : TCriticalSection;<br />anInt: integer;<br />aList: TList;</p>
<p><font color="Green">//create the CriticalSection when my class is created</font><br />TMyClass.Create<br />begin<br />  cs := TCriticalSection.Create;<br />end;</p>
<p><font color="Green">//thread wants to access the int</font><br />cs.Enter;<br />doSomethingtoInt(anInt);<br />cs.leave;</p>
<p><font color="Green">//thread want sto do something to the TList</font><br />cs.Enter;<br />aList.add(anItem);<br />cs.Leave;</p>
<p><font color="Red"><b>This is very wrong for the following reasons (and probably more):</b></font><br />1) I should have use a TThreadSafeList with auto locking built in for thread safe use<br />2) Using the <b>same</b> CriticalSection on two <b>different</b> sections of data is completely wrong.  Each data that needs locking and is used in different routines or accessed at different times should have it&#8217;s own CriticalSection like so:</p>
<p><font color="Green">//Global vars</font><br />var<br />iCS : TCriticalSection;<br />lCS : TCriticalSection<br />anInt: integer;<br />aList: TList;</p>
<p><font color="Green">//create the CriticalSection when my class was created</font><br />TMyClass.Create<br />begin<br />  iCS := TCriticalSection.Create;<br />  lCS := TCriticalSection.Create;<br />end;</p>
<p><font color="Green">//thread wants to access the int</font><br />iCS.Enter;<br />doSomethingtoInt(anInt);<br />iCS.leave;</p>
<p><font color="Green">//thread wants to do something to the TList</font><br />aCS.Enter;<br />aList.add(anItem);<br />aCS.Leave;</p>
<p>Again, I must stress that if you need to use a TList with threads a much saner and safer option is to use a TThreadSafeList which locks the contained TList for you.  If you need to access the internal TList of a TThreadSafeList the following code works great:</p>
<p>with threadedList.LockList do<br />    try<br />      for x := 0 to Count &#8211; 1 do begin<br />        doSomething(items[x]);<br />      end;<br />    finally<br />      threadedList.UnlockList;<br />    end;</p>
<p>However simple actions such as adding an item are like so:</p>
<p>threadedList.Add(anItem);</p>
<p>A simple unit containing a class that spawns several threads and uses TCriticalSections to protect the data would look like so:<br />
<blockquote>unit myClassUnit;</p>
<p>interface<br />uses<br />SyncObjs;</p>
<p>type<br />myClass = class<br />  private<br />    anInt: Integer;<br />    aWord: word;<br />    intCS: TCriticalSection;<br />    wordCS: TCriticalSection;<br />  public<br />    Constructor Create;<br />    Destructor Destroy;<br />    Procedure IncInt;<br />    Procedure IncWord;<br />    procedure decInt;<br />    Procedure spawnThread;<br />end;</p>
<p>implementation</p>
<p>{ myClass }</p>
<p>constructor myClass.Create;<br />begin<br />  anInt := 0;<br />  aWord := 0;<br />  intCS := TCriticalSection.Create;<br />  wordCS := TCriticalSection.Create;<br />end;</p>
<p>destructor myClass.Destroy;<br />begin<br />  intCS.Free;<br />  wordCS.Free;<br />end;</p>
<p>procedure myClass.decInt;<br />begin<br />  intCS.Enter;<br />  dec(anInt);<br />  intCS.Leave;<br />end;</p>
<p>procedure myClass.IncInt;<br />begin<br />  intCs.Enter;<br />  inc(anInt);<br />  intCS.Leave;<br />end;</p>
<p>procedure myClass.IncWord;<br />begin<br />  wordCS.Enter;<br />  inc(aWord);<br />  wordCS.Leave;<br />end;</p>
<p>procedure myClass.spawnThread;<br />var<br />  aThread : TMyThread;<br />begin<br />  aThread := TMyThread.Create(False);<br />end;</p>
<p>end.</p></blockquote>
<p>Usage would be as simple as</p>
<p>var<br />theClass : TMyClass;<br />x : integer;<br />begin<br />theClass := TMyClass.Create;<br />for x := 0 to 3 do begin<br />theClass.spawnThread;<br />end;</p>
<p>with the threads calling the inc or dec procedures like so:</p>
<p>theClass.incInt;<br />theClass.decInt;<br />theClass.incWord;</p>
<p>with no risk of data corruption being caused by multiple or conflicting calls to the procedures by different threads.</p>
<!-- AdSense Now! V1.90 -->
<!-- Post[count: 2] -->
<div class="adsense adsense-leadout" style="text-align:center;margin: 12px;"><script type="text/javascript"><!--
google_ad_client = "pub-5905155743931046";
/* 468x15, created 10/04/10 */
google_ad_slot = "2193001556";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.gothi.co.uk/2006/10/using-critical-sections-with-delphi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

