<?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>Artful Code &#187; threads</title>
	<atom:link href="http://www.artfulcode.net/tags/threads/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.artfulcode.net</link>
	<description>Resources and tips for dynamic, interactive languages.</description>
	<lastBuildDate>Fri, 09 Sep 2011 02:15:45 +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>Thread pool module for Pike</title>
		<link>http://www.artfulcode.net/articles/thread-pool-module-for-pike/</link>
		<comments>http://www.artfulcode.net/articles/thread-pool-module-for-pike/#comments</comments>
		<pubDate>Tue, 10 Mar 2009 17:14:09 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[pike]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.artfulcode.net/?p=572</guid>
		<description><![CDATA[Async provides a simple process pool that allocates a number of worker threads
that may then be utilized collectively without having to deal directly with
threads. Results of jobs sent to the pool are "future" objects, called Asyncs.
Asyncs' values are then acquired by calling Async.sync, which blocks until the
value has been set by the pool. A supervisor thread monitors the worker threads
and restarts any that terminate abnormally.]]></description>
			<content:encoded><![CDATA[<h2>Async.pmod</h2>
<p>Download it <a href="http://www.artfulcode.net/wp-content/uploads/2009/03/async.pmod">here</a>.</p>
<p>Async provides a simple process pool that allocates a number of worker threads<br />
that may then be utilized collectively without having to deal directly with<br />
threads. Results of jobs sent to the pool are &#8220;future&#8221; objects, called Asyncs.<br />
Asyncs&#8217; values are then acquired by calling Async.sync, which blocks until the<br />
value has been set by the pool. A supervisor thread monitors the worker threads<br />
and restarts any that terminate abnormally.<span id="more-572"></span></p>
<p>Usage is simple:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// create a pool of four processes</span>
Pool pool <span style="color: #339933;">=</span> Pool<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">4</span><span style="color: #009900;">&#41;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// send a job to the pool</span>
Async result <span style="color: #339933;">=</span> Pool<span style="color: #339933;">-&gt;</span>send<span style="color: #009900;">&#40;</span>exp<span style="color: #339933;">,</span> <span style="color: #0000dd;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// get the result</span>
result<span style="color: #339933;">-&gt;</span>sync<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// =&gt; 22026.46484375</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// alternately, you can call an async</span>
result<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// =&gt; 22026.46484375</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// pools can conveniently map across a sequence</span>
Async mapped_result <span style="color: #339933;">=</span> pool<span style="color: #339933;">-&gt;</span>map<span style="color: #009900;">&#40;</span>exp<span style="color: #339933;">,</span> enumerate<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
mapped_result<span style="color: #339933;">-&gt;</span>sync<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// =&gt; ({ 1.0, 2.718281745910645, 7.389056205749512, 20.08553695678711, 54.59814834594727 })</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// or iterate without collecting return values</span>
<span style="color: #993333;">int</span> x <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
pool<span style="color: #339933;">-&gt;</span>iter<span style="color: #009900;">&#40;</span>lambda <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> x <span style="color: #339933;">+=</span> n<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> enumerate<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">100</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
write<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d&quot;</span><span style="color: #339933;">,</span> x<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// =&gt; 4950</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// close the pool, blocking until all workers have terminated</span>
pool<span style="color: #339933;">-&gt;</span>close<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Submit article</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthread-pool-module-for-pike%2F&amp;title=Thread+pool+module+for+Pike" rel="nofollow" title="Add to&nbsp;Del.icio.us"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/delicious.png" title="Add to&nbsp;Del.icio.us" alt="Add to&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthread-pool-module-for-pike%2F&amp;title=Thread+pool+module+for+Pike" rel="nofollow" title="Add to&nbsp;digg"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/digg.png" title="Add to&nbsp;digg" alt="Add to&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.dzone.com/links/add.html?description=Thread+pool+module+for+Pike&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthread-pool-module-for-pike%2F&amp;title=Thread+pool+module+for+Pike" rel="nofollow" title="Add to&nbsp;DZone"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/dzone.png" title="Add to&nbsp;DZone" alt="Add to&nbsp;DZone" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthread-pool-module-for-pike%2F" rel="nofollow" title="Add to&nbsp;Facebook"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/facebook.png" title="Add to&nbsp;Facebook" alt="Add to&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthread-pool-module-for-pike%2F&amp;title=Thread+pool+module+for+Pike" rel="nofollow" title="Add to&nbsp;reddit"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/reddit.png" title="Add to&nbsp;reddit" alt="Add to&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthread-pool-module-for-pike%2F&amp;title=Thread+pool+module+for+Pike" rel="nofollow" title="Add to&nbsp;Stumble Upon"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Add to&nbsp;Stumble Upon" alt="Add to&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthread-pool-module-for-pike%2F" rel="nofollow" title="Add to&nbsp;Technorati"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/technorati.png" title="Add to&nbsp;Technorati" alt="Add to&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Thread+pool+module+for+Pike+@+http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthread-pool-module-for-pike%2F" rel="nofollow" title="Add to&nbsp;Twitter"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/twitter.png" title="Add to&nbsp;Twitter" alt="Add to&nbsp;Twitter" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.artfulcode.net/articles/thread-pool-module-for-pike/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiprocessing utilities for newLisp</title>
		<link>http://www.artfulcode.net/articles/multiprocessing-utilities-for-newlisp/</link>
		<comments>http://www.artfulcode.net/articles/multiprocessing-utilities-for-newlisp/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 17:39:26 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[newlisp]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.artfulcode.net/?p=533</guid>
		<description><![CDATA[newLisp's Cilk API simplifies the task for forking new processes and retrieving the results of child processes' calculations a breeze. Some patterns remain complex, particularly when dealing with shared state or managing access to resources. To formalize some of the more common patterns of usage with the Cilk API, semaphores, and shared memory, I have written a multiprocessing library for newLisp.]]></description>
			<content:encoded><![CDATA[<p>newLisp&#8217;s Cilk API simplifies the task for forking new processes and retrieving the results of child processes&#8217; calculations a breeze. Some patterns remain complex, particularly when dealing with shared state or managing access to resources. To formalize some of the more common patterns of usage with the Cilk API, semaphores, and shared memory, I have written a multiprocessing library for newLisp.<span id="more-533"></span></p>
<p>The module came out of my original locks module, which contained only the Lock and RLock classes. The new library contains the following classes:</p>
<ul>
<li><strong>Semaphore:</strong> simplifies use of semaphores</li>
<li><strong>Shared:</strong> simplifies use of shared memory</li>
<li><strong>Synchronized:</strong> shared memory made safe for use between processes</li>
<li><strong>Lock:</strong> a binary semaphore, or mutex</li>
<li><strong>RLock:</strong> a recursive Lock</li>
<li><strong>Event:</strong> a simple mechanism to signal multiple processes</li>
<li><strong>Pipe:</strong> simplifies use of pipes</li>
<li><strong>Channel:</strong> a two-way communications channel made with pipes</li>
<li><strong>Queue:</strong> a synchronized first in, first out class</li>
</ul>
<p>MP additionally includes various utilities to deal with common tasks:</p>
<ul>
<li><strong>get-pid:</strong> gets the current processes&#8217; pid</li>
<li><strong>with-lock-held:</strong> a macro that evaluates its body while holding a lock</li>
<li><strong>wait:</strong> waits for a condition with variable length polling to reduce processor load</li>
<li><strong>map and iter:</strong> versions of map and dolist evaluated asynchronously using the Cilk API</li>
</ul>
<p>Perhaps the most useful function in the module is with-lock-held, which simplifies the most common locking case: assuring that a block of code is executed atomically.</p>

<div class="wp_syntax"><div class="code"><pre class="newlisp" style="font-family:monospace;"><span style="color: #AF0500;">&#40;</span><span style="color: #2028B8;">setf</span> lock <span style="color: #AF0500;">&#40;</span>RLock<span style="color: #AF0500;">&#41;</span><span style="color: #AF0500;">&#41;</span>
<span style="color: #AF0500;">&#40;</span>with-lock-held lock
  <span style="color: #AF0500;">&#40;</span>access-restricted-resource<span style="color: #AF0500;">&#41;</span><span style="color: #AF0500;">&#41;</span></pre></div></div>

<p>In this case, no more than one process can evaluate <code>(access-restricted-resource)</code> at a time.</p>
<p>You can download the <a href="http://static.artfulcode.net/newlisp/mp.lsp.html">MP module</a> from my <a href="http://static.artfulcode.net/newlisp/index.html">newLisp module repository</a>.</p>
<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Submit article</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmultiprocessing-utilities-for-newlisp%2F&amp;title=Multiprocessing+utilities+for+newLisp" rel="nofollow" title="Add to&nbsp;Del.icio.us"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/delicious.png" title="Add to&nbsp;Del.icio.us" alt="Add to&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmultiprocessing-utilities-for-newlisp%2F&amp;title=Multiprocessing+utilities+for+newLisp" rel="nofollow" title="Add to&nbsp;digg"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/digg.png" title="Add to&nbsp;digg" alt="Add to&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.dzone.com/links/add.html?description=Multiprocessing+utilities+for+newLisp&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmultiprocessing-utilities-for-newlisp%2F&amp;title=Multiprocessing+utilities+for+newLisp" rel="nofollow" title="Add to&nbsp;DZone"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/dzone.png" title="Add to&nbsp;DZone" alt="Add to&nbsp;DZone" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmultiprocessing-utilities-for-newlisp%2F" rel="nofollow" title="Add to&nbsp;Facebook"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/facebook.png" title="Add to&nbsp;Facebook" alt="Add to&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmultiprocessing-utilities-for-newlisp%2F&amp;title=Multiprocessing+utilities+for+newLisp" rel="nofollow" title="Add to&nbsp;reddit"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/reddit.png" title="Add to&nbsp;reddit" alt="Add to&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmultiprocessing-utilities-for-newlisp%2F&amp;title=Multiprocessing+utilities+for+newLisp" rel="nofollow" title="Add to&nbsp;Stumble Upon"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Add to&nbsp;Stumble Upon" alt="Add to&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmultiprocessing-utilities-for-newlisp%2F" rel="nofollow" title="Add to&nbsp;Technorati"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/technorati.png" title="Add to&nbsp;Technorati" alt="Add to&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Multiprocessing+utilities+for+newLisp+@+http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmultiprocessing-utilities-for-newlisp%2F" rel="nofollow" title="Add to&nbsp;Twitter"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/twitter.png" title="Add to&nbsp;Twitter" alt="Add to&nbsp;Twitter" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.artfulcode.net/articles/multiprocessing-utilities-for-newlisp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An overview of threading in Pike</title>
		<link>http://www.artfulcode.net/articles/an-overview-of-threading-in-pike/</link>
		<comments>http://www.artfulcode.net/articles/an-overview-of-threading-in-pike/#comments</comments>
		<pubDate>Thu, 04 Sep 2008 13:17:24 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[pike]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.artfulcode.net/articles/overview-threading-pike/</guid>
		<description><![CDATA[Pike&#8217;s approach to threading is simple and mindful of the sanity of the programmer. Threading is available for all systems using Unix, POSIX, or Windows threads. The Thread module in the standard library provides a complete system for multi-threading. Initially, a thread is created by instantiating a new instance of the Thread.Thread class with a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://pike.ida.liu.se/">Pike&#8217;s</a> approach to threading is simple and mindful of the sanity of the programmer.  Threading is available for all systems using Unix, POSIX, or Windows threads.<span id="more-13"></span></p>
<p>The <code>Thread</code> module in the standard library provides a complete system for multi-threading.  Initially, a thread is created by instantiating a new instance of the <code>Thread.Thread</code> class with a function that will be executed in a new thread and any arguments to that function:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> say_hello<span style="color: #009900;">&#40;</span><span style="color: #993333;">string</span> name<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    write<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Hello, &quot;</span> <span style="color: #339933;">+</span> name <span style="color: #339933;">+</span> <span style="color: #ff0000;">&quot;.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    Thread.<span style="color: #202020;">Thread</span> thread<span style="color: #339933;">;</span>
    thread <span style="color: #339933;">=</span> Thread.<span style="color: #202020;">Thread</span><span style="color: #009900;">&#40;</span>say_hello<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Jeff&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// return -1 so execution does not terminate</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Pike&#8217;s interpreter is completely thread-safe.  All execution is protected by a global interpreter lock, similar to that of Python.  Unlike Python, however, Pike&#8217;s locking is finely grained and released often, making threads quite useful in Pike.</p>
<h4>Thread.Mutex and Thread.MutexKey</h4>
<p>Mutexes are required to protect critical sections that must be executed atomically.  Thanks to the interpreter lock, no two threads will ever access the same variable concurrently.  However, if a variable is modified or accessed multiple times in a thread, a mutex must be used to guard it:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">Thread.<span style="color: #202020;">Mutex</span> m <span style="color: #339933;">=</span> Thread.<span style="color: #202020;">Mutex</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// create a mutex</span>
<span style="color: #993333;">void</span> func<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    Thread.<span style="color: #202020;">MutexKey</span> k <span style="color: #339933;">=</span> m<span style="color: #339933;">-&gt;</span>lock<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// acquire the lock</span>
&nbsp;
    ... <span style="color: #666666; font-style: italic;">// do stuff</span>
    ... <span style="color: #666666; font-style: italic;">// do more stuff</span>
&nbsp;
    <span style="color: #b1b100;">return</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Notice that the mutex was never released.  Once the <code>MutexKey</code> (returned by <code>Mutex->lock()</code>) goes out of scope, the mutex is automatically released.  This means that a method can be made to be synchronized simply by acquiring a lock at the beginning of the function.</p>
<h4>Thread.Condition</h4>
<p>Condition variables are used to synchronize events across multiple threads.  A thread controlling a resource holds a condition variable, with other threads waiting for the condition to be signaled.  The controlling thread may chose to signal just one or all waiting threads at once.</p>
<p>A <code>MutexKey</code> must be provided by the waitin thread to guarantee synchronicity with the signaling thread.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">Thread.<span style="color: #202020;">Mutex</span> mutex <span style="color: #339933;">=</span> Thread.<span style="color: #202020;">Mutex</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">void</span> consumer<span style="color: #009900;">&#40;</span>Thread.<span style="color: #202020;">Condition</span> c<span style="color: #339933;">,</span> Thread.<span style="color: #202020;">Condition</span> c2<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Thread.<span style="color: #202020;">MutexKey</span> key <span style="color: #339933;">=</span> mutex<span style="color: #339933;">-&gt;</span>lock<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        c<span style="color: #339933;">-&gt;</span>wait<span style="color: #009900;">&#40;</span>key<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        key <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        write<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Pong!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        c2<span style="color: #339933;">-&gt;</span>signal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> producer<span style="color: #009900;">&#40;</span>Thread.<span style="color: #202020;">Condition</span> c<span style="color: #339933;">,</span> Thread.<span style="color: #202020;">Condition</span> c2<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Thread.<span style="color: #202020;">MutexKey</span> key <span style="color: #339933;">=</span> mutex<span style="color: #339933;">-&gt;</span>lock<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        c2<span style="color: #339933;">-&gt;</span>wait<span style="color: #009900;">&#40;</span>key<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        key <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        write<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Ping!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        c<span style="color: #339933;">-&gt;</span>signal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    Thread.<span style="color: #202020;">Condition</span> condition1<span style="color: #339933;">,</span> condition2<span style="color: #339933;">;</span>
    Thread.<span style="color: #202020;">Thread</span> prod<span style="color: #339933;">,</span> cons<span style="color: #339933;">;</span>
    condition1 <span style="color: #339933;">=</span> Thread.<span style="color: #202020;">Condition</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    condition2 <span style="color: #339933;">=</span> Thread.<span style="color: #202020;">Condition</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    prod <span style="color: #339933;">=</span> Thread.<span style="color: #202020;">Thread</span><span style="color: #009900;">&#40;</span>producer<span style="color: #339933;">,</span> condition1<span style="color: #339933;">,</span> condition2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    cons <span style="color: #339933;">=</span> Thread.<span style="color: #202020;">Thread</span><span style="color: #009900;">&#40;</span>consumer<span style="color: #339933;">,</span> condition1<span style="color: #339933;">,</span> condition2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    condition2<span style="color: #339933;">-&gt;</span>signal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// get the producer started</span>
    <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// keeps script running</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In this way, a condition variable is akin to a simplified <a href="http://en.wikipedia.org/wiki/Counting_semaphore">counting semaphore</a>, which may be incremented n times to signal n waiting threads.</p>
<h4>Thread.Local</h4>
<p>Thread-local storage may be created with <code>Thread.Local</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">string</span> thread_fn<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    Thread.<span style="color: #202020;">Local</span> data <span style="color: #339933;">=</span> Thread.<span style="color: #202020;">Local</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    data<span style="color: #339933;">-&gt;</span>set<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;foo&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> data<span style="color: #339933;">-&gt;</span>get<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h4>Thread.Queue</h4>
<p>Queues are first in, first out containers.<br />
<code>Thread.Queue</code> is expandable, so pushing new elements into the queue will not block:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> consumer<span style="color: #009900;">&#40;</span>Thread.<span style="color: #202020;">Queue</span> q<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #993333;">string</span> value <span style="color: #339933;">=</span> q<span style="color: #339933;">-&gt;</span>read<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// block until value available</span>
        do_something_with<span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Another interesting method is <code>read_array</code>, which reads as many values as are available.  This is extremely useful.  Reading a batch of work results in less time spend blocking, making active queues much more efficient.</p>
<h4>Thread.Fifo</h4>
<p>The primary difference between the <code>Queue</code> and <code>Fifo</code> classes is that the <code>Fifo</code> class is bounded and will block on writes when full.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> producer<span style="color: #009900;">&#40;</span>Thread.<span style="color: #202020;">Fifo</span> q<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">string</span> value<span style="color: #339933;">;</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        value <span style="color: #339933;">=</span> get_value_from_somewhere<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        q<span style="color: #339933;">-&gt;</span>write<span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// blocks until space is available</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h4>Conclusion</h4>
<p>Pike makes threading easy on programmers.  Pike&#8217;s internals are thread-safe; a programmer never needs to worry about corrupting memory.  Mutually exclusive locks are only used to protect blocks of code that must be executed without interruption, so that only the concurrency of the overall technique must be considered.</p>
<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Submit article</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fan-overview-of-threading-in-pike%2F&amp;title=An+overview+of+threading+in+Pike" rel="nofollow" title="Add to&nbsp;Del.icio.us"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/delicious.png" title="Add to&nbsp;Del.icio.us" alt="Add to&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fan-overview-of-threading-in-pike%2F&amp;title=An+overview+of+threading+in+Pike" rel="nofollow" title="Add to&nbsp;digg"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/digg.png" title="Add to&nbsp;digg" alt="Add to&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.dzone.com/links/add.html?description=An+overview+of+threading+in+Pike&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fan-overview-of-threading-in-pike%2F&amp;title=An+overview+of+threading+in+Pike" rel="nofollow" title="Add to&nbsp;DZone"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/dzone.png" title="Add to&nbsp;DZone" alt="Add to&nbsp;DZone" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fan-overview-of-threading-in-pike%2F" rel="nofollow" title="Add to&nbsp;Facebook"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/facebook.png" title="Add to&nbsp;Facebook" alt="Add to&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fan-overview-of-threading-in-pike%2F&amp;title=An+overview+of+threading+in+Pike" rel="nofollow" title="Add to&nbsp;reddit"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/reddit.png" title="Add to&nbsp;reddit" alt="Add to&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fan-overview-of-threading-in-pike%2F&amp;title=An+overview+of+threading+in+Pike" rel="nofollow" title="Add to&nbsp;Stumble Upon"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Add to&nbsp;Stumble Upon" alt="Add to&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fan-overview-of-threading-in-pike%2F" rel="nofollow" title="Add to&nbsp;Technorati"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/technorati.png" title="Add to&nbsp;Technorati" alt="Add to&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+An+overview+of+threading+in+Pike+@+http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fan-overview-of-threading-in-pike%2F" rel="nofollow" title="Add to&nbsp;Twitter"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/twitter.png" title="Add to&nbsp;Twitter" alt="Add to&nbsp;Twitter" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.artfulcode.net/articles/an-overview-of-threading-in-pike/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Locking with semaphores in newLISP</title>
		<link>http://www.artfulcode.net/articles/locking-semaphores-newlisp/</link>
		<comments>http://www.artfulcode.net/articles/locking-semaphores-newlisp/#comments</comments>
		<pubDate>Wed, 04 Jun 2008 19:46:55 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[newlisp]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.artfulcode.net/articles/locking-semaphores-newlisp/</guid>
		<description><![CDATA[Recent development version of newLISP have a new forking mechanism that makes spawning new processes and collecting the results much simpler. However, for long-running processes that intermittently access shared data (for example, using the (share) function), semaphores are used to lock that data. Technically, newLISP semaphores are counting semaphores (semaphores that may be incremented above [...]]]></description>
			<content:encoded><![CDATA[<p>Recent development version of newLISP have a <a href="http://www.artfulcode.net/articles/newlisp-get-cilk-style-concurrency/">new forking mechanism</a> that makes spawning new processes and collecting the results much simpler.<span id="more-23"></span></p>
<p>However, for long-running processes that intermittently access shared data (for example, using the <code>(share)</code> function), semaphores are used to lock that data.  Technically, newLISP semaphores are counting semaphores (semaphores that may be incremented above 1), rather than binary semaphores (which are the equivalent of mutually exclusive locks).</p>
<p>These functions that wrap the semaphore command.  They function as binary semaphores.  Included is a macro <code>with-lock-held</code>, which executes its body with the passed lock acquired.</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>constant 'ACQUIRE -<span style="color: #cc66cc;">1</span> 'RELEASE <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">;;; Convenience functions, macros</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>define-macro <span style="color: #66cc66;">&#40;</span>with-lock-held<span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span>letex <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>lock <span style="color: #66cc66;">&#40;</span>args <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>body <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">cons</span> 'begin <span style="color: #66cc66;">&#40;</span>rest <span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">:</span><span style="color: #555;">acquire</span> lock<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>res body<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">:</span><span style="color: #555;">release</span> lock<span style="color: #66cc66;">&#41;</span>
      res<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>define <span style="color: #66cc66;">&#40;</span>getpid<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>sys-info <span style="color: #cc66cc;">6</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>global 'with-lock-held 'getpid<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">;;; Locks are generic binary-style semaphores like mutexes.</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>define <span style="color: #66cc66;">&#40;</span>Lock<span style="color: #66cc66;">:</span><span style="color: #555;">Lock</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>sem <span style="color: #66cc66;">&#40;</span>semaphore<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>pid <span style="color: #66cc66;">&#40;</span>share<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>semaphore sem RELEASE<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>share pid <span style="color: #b1b100;">nil</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">list</span> <span style="color: #66cc66;">&#40;</span>context<span style="color: #66cc66;">&#41;</span> sem pid<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>define <span style="color: #66cc66;">&#40;</span>Lock<span style="color: #66cc66;">:</span><span style="color: #555;">acquire</span> lock<span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span>semaphore <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> ACQUIRE<span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span>share <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>getpid<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>define <span style="color: #66cc66;">&#40;</span>Lock<span style="color: #66cc66;">:</span><span style="color: #555;">release</span> lock<span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#40;</span>getpid<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>share <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>begin
      <span style="color: #66cc66;">&#40;</span>semaphore <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> RELEASE<span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#40;</span>share <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">nil</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>throw-<span style="color: #b1b100;">error</span> <span style="color: #ff0000;">&quot;Cannot release lock that is locked by another process.&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">;;; Recursive locks (RLocks) are locks that &quot;owned&quot; by a</span>
<span style="color: #808080; font-style: italic;">;;; locking process and are not re-locked by subsequent code</span>
<span style="color: #808080; font-style: italic;">;;; in the same process.</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>define <span style="color: #66cc66;">&#40;</span>RLock<span style="color: #66cc66;">:</span><span style="color: #555;">RLock</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>sem <span style="color: #66cc66;">&#40;</span>semaphore<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>depth <span style="color: #66cc66;">&#40;</span>semaphore<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>pid <span style="color: #66cc66;">&#40;</span>share<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>semaphore sem RELEASE<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>semaphore depth <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>share pid <span style="color: #b1b100;">nil</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">list</span> <span style="color: #66cc66;">&#40;</span>context<span style="color: #66cc66;">&#41;</span> sem depth pid<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>define <span style="color: #66cc66;">&#40;</span>RLock<span style="color: #66cc66;">:</span><span style="color: #555;">acquire</span> lock<span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>sem <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>depth <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>pid <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#40;</span>share pid<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>getpid<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#40;</span>semaphore depth <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#40;</span>begin
        <span style="color: #66cc66;">&#40;</span>semaphore sem ACQUIRE<span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span>semaphore depth <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span>share pid <span style="color: #66cc66;">&#40;</span>getpid<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>define <span style="color: #66cc66;">&#40;</span>RLock<span style="color: #66cc66;">:</span><span style="color: #555;">release</span> lock<span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>sem <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>depth <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>pid <span style="color: #66cc66;">&#40;</span>lock <span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#40;</span>share pid<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>getpid<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#40;</span>begin
        <span style="color: #66cc66;">&#40;</span>semaphore depth -<span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">when</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">0</span> <span style="color: #66cc66;">&#40;</span>semaphore depth<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
          <span style="color: #66cc66;">&#40;</span>share pid <span style="color: #b1b100;">nil</span><span style="color: #66cc66;">&#41;</span>
          <span style="color: #66cc66;">&#40;</span>semaphore sem RELEASE<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
      <span style="color: #66cc66;">&#40;</span>throw-<span style="color: #b1b100;">error</span> <span style="color: #ff0000;">&quot;Cannot release rlock that is locked by another process.&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Here is a quick sample of how to use the locks to synchronize access to a page of shared memory:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">;;; create a shared resource that to be protected by a lock</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">setq</span> mem <span style="color: #66cc66;">&#40;</span>share<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">setq</span> mem-lock <span style="color: #66cc66;">&#40;</span>Lock<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">:</span><span style="color: #555;">acquire</span> mem-lock<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span>share mem <span style="color: #ff0000;">&quot;foo&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span>spawn 's
  <span style="color: #66cc66;">&#40;</span>begin
    <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">:</span><span style="color: #555;">acquire</span> mem-lock<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span>share mem <span style="color: #ff0000;">&quot;bar&quot;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">:</span><span style="color: #555;">release</span> mem-lock<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #808080; font-style: italic;">;;; at this point, the spawned process is blocking, waiting for us</span>
<span style="color: #808080; font-style: italic;">;;; to release mem-lock. mem still holds &quot;foo&quot;</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">:</span><span style="color: #555;">release</span> mem-lock<span style="color: #66cc66;">&#41;</span>
<span style="color: #808080; font-style: italic;">;;; now, the spawned process continues, and sets mem to &quot;bar&quot;</span></pre></div></div>

<p>The same may be done more concisely using <code>with-lock-held</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">;;; create a shared resource that to be protected by a lock</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">setq</span> mem <span style="color: #66cc66;">&#40;</span>share<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">setq</span> mem-lock <span style="color: #66cc66;">&#40;</span>Lock<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>with-lock-held mem-lock
  <span style="color: #66cc66;">&#40;</span>share mem <span style="color: #ff0000;">&quot;foo&quot;</span><span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span>spawn 's
    <span style="color: #66cc66;">&#40;</span>with-lock-held mem-lock
      <span style="color: #66cc66;">&#40;</span>share mem <span style="color: #ff0000;">&quot;bar&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p><a href="/wp-content/uploads/2008/12/lockslsp.gz">download</a></p>
<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Submit article</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Flocking-semaphores-newlisp%2F&amp;title=Locking+with+semaphores+in+newLISP" rel="nofollow" title="Add to&nbsp;Del.icio.us"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/delicious.png" title="Add to&nbsp;Del.icio.us" alt="Add to&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Flocking-semaphores-newlisp%2F&amp;title=Locking+with+semaphores+in+newLISP" rel="nofollow" title="Add to&nbsp;digg"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/digg.png" title="Add to&nbsp;digg" alt="Add to&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.dzone.com/links/add.html?description=Locking+with+semaphores+in+newLISP&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Flocking-semaphores-newlisp%2F&amp;title=Locking+with+semaphores+in+newLISP" rel="nofollow" title="Add to&nbsp;DZone"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/dzone.png" title="Add to&nbsp;DZone" alt="Add to&nbsp;DZone" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Flocking-semaphores-newlisp%2F" rel="nofollow" title="Add to&nbsp;Facebook"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/facebook.png" title="Add to&nbsp;Facebook" alt="Add to&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Flocking-semaphores-newlisp%2F&amp;title=Locking+with+semaphores+in+newLISP" rel="nofollow" title="Add to&nbsp;reddit"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/reddit.png" title="Add to&nbsp;reddit" alt="Add to&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Flocking-semaphores-newlisp%2F&amp;title=Locking+with+semaphores+in+newLISP" rel="nofollow" title="Add to&nbsp;Stumble Upon"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Add to&nbsp;Stumble Upon" alt="Add to&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Flocking-semaphores-newlisp%2F" rel="nofollow" title="Add to&nbsp;Technorati"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/technorati.png" title="Add to&nbsp;Technorati" alt="Add to&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Locking+with+semaphores+in+newLISP+@+http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Flocking-semaphores-newlisp%2F" rel="nofollow" title="Add to&nbsp;Twitter"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/twitter.png" title="Add to&nbsp;Twitter" alt="Add to&nbsp;Twitter" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.artfulcode.net/articles/locking-semaphores-newlisp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Threading in Django</title>
		<link>http://www.artfulcode.net/articles/threading-django/</link>
		<comments>http://www.artfulcode.net/articles/threading-django/#comments</comments>
		<pubDate>Fri, 07 Mar 2008 16:46:00 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.artfulcode.net/articles/threading-django/</guid>
		<description><![CDATA[Profitable use of threading in web development is rare, particularly when contending with Python&#8217;s global interpreter lock. There are a few notable exceptions to this. The global interpreter lock (GIL) is the method that Python uses to maintain internal thread-safety when not all Python objects are thread-safe. The GIL ensures that no Python object may [...]]]></description>
			<content:encoded><![CDATA[<p>Profitable use of threading in web development is rare, particularly when contending with Python&#8217;s global interpreter lock.  There are a few notable exceptions to this.<span id="more-30"></span></p>
<p>The global interpreter lock (GIL) is the method that Python uses to maintain internal thread-safety when not all Python objects are thread-safe.  The GIL ensures that no Python object may be modified by multiple threads at the same time.  This is transparent to the Python programmer; the GIL is locking internal structures.  A list that is modified by multiple threads without explicit locking will still behave erratically.</p>
<p>This makes threading less useful in web development.  Because Python can not directly maintain state between reqeusts (indirectly, via the client, state may be maintained using session cookies or other similar strategies), each request is a new thread:</p>
<pre><code> 1. Determine what data is being requested
 2. Get the data
 3. Format the data
 4. Send the data
</code></pre>
<p>Each of these steps depends on the state information from the previous step.  There is not a lot of room for asynchronicity.  The usefulness of threading is pushed back to the web server.  That is where integrated server/framework solutions, like <a href="http://www.ocsigen.org/">Ocsigen</a>, have an advantage.</p>
<p>Many web-based applications, however, are not simple database front ends.  There are a few common situations where threading becomes useful; specifically, when there are side effects of a request.</p>
<p>On a side note, experts will tell you that only POST request should result in side effects.  This is misleading.  POST should certainly be used for user-intended side effects.  However, what happends when there is an error loading a page?</p>
<h4>Error messages</h4>
<p>In the event of a coding or environment error, Django sends me an email.  This is a wonderful (and an occassionally annoying) feature.  But what if the problem is caused by the data we input, rather than the code?  I can detect this in my code and present the user with a nice error page apologizing for the inconvenience, but now I want to notify the content team that an entry in the database is invalid in some way.</p>
<p>Sending a message, especially if Django is connecting to a remote mail server, can take a while.  This is a good use for threading.  The thread should deal with as little data processing as possible, concentrating instead on the side effect.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">threading</span>
<span style="color: #ff7700;font-weight:bold;">from</span> django.<span style="color: black;">core</span>.<span style="color: black;">mail</span> <span style="color: #ff7700;font-weight:bold;">import</span> send_mail
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> foo<span style="color: black;">&#40;</span>request, identifier<span style="color: black;">&#41;</span>:
    data = get_some_data<span style="color: black;">&#40;</span>identifier<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        error_check<span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span> <span style="color: #808080; font-style: italic;"># raise exception if data invalid</span>
    <span style="color: #ff7700;font-weight:bold;">except</span> InvalidData, e:
        <span style="color: #808080; font-style: italic;"># Format our information here, in the main thread</span>
        subject = <span style="color: #483d8b;">&quot;Invalid data in entry %d&quot;</span> <span style="color: #66cc66;">%</span> identifier
        message = <span style="color: #483d8b;">&quot;&quot;&quot;
            There is an error in entry %d.  Please check this
            data at http://path/to/django/admin/app/table/%d.
        &quot;&quot;&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>identifier, identifier<span style="color: black;">&#41;</span>
        recipients = <span style="color: black;">&#91;</span><span style="color: #483d8b;">'someone@somewere.com'</span>, <span style="color: #483d8b;">'someoneelse@somewhere.com'</span><span style="color: black;">&#93;</span>
        <span style="color: #ff7700;font-weight:bold;">from</span> = <span style="color: #483d8b;">'root@server.com'</span>
&nbsp;
        <span style="color: #808080; font-style: italic;"># Create a new thread in Daemon mode to send message</span>
        t = <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#40;</span>target=send_mail,
                             args=<span style="color: black;">&#91;</span>subject, message, <span style="color: #ff7700;font-weight:bold;">from</span>, recipients<span style="color: black;">&#93;</span>,
                             kwargs=<span style="color: black;">&#123;</span><span style="color: #483d8b;">'fail_silently'</span>: <span style="color: #008000;">True</span><span style="color: black;">&#125;</span><span style="color: black;">&#41;</span>
        t.<span style="color: black;">setDaemon</span><span style="color: black;">&#40;</span><span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
        t.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> HttpResponseServerError<span style="color: black;">&#40;</span>some_error_page<span style="color: black;">&#41;</span></pre></div></div>

<p>Note particularly that we use <code>t.setDaemon(True)</code> on the thread before starting it.  This tells Python not to wait for the thread to exit before returning data to the client.</p>
<h4>Writing files</h4>
<p>Many of our web-based programs write data to static files.  Some applications maintain logs.  Others publish static HTML files to the enterprise server.  These are great uses for Python threads, since the GIL is released during file IO operations.</p>
<h4>Caching remote data</h4>
<p>We are a large business and applications are developed by various (often isolated) units.  I often find myself in a situation where my application depends on mutable data extracted from another system but does not have direct access to the data&#8217;s database.</p>
<p>Rather than depend on low internal network latencies and download the data extract on each page load, I cache the data and keep a local copy, using a script to synchronize the data.  For simple data, this can be stored using Django&#8217;s low level cache.  But if some state needs to be maintained for that data, a database table is a better method.</p>
<p>When there are a large number of such objects, a scheduled update process becomes burdensome, especially if the number of objects increases regularly.  Therefore, the solution is to trigger the event when the data is accessed (via a page load).</p>
<p>Each cached database entry gets a timestamp field to note its last update.  The model defines an update method and the model manager&#8217;s <code>get()</code> method checks the entry&#8217;s timestamp to see if the data needs to be freshened.  The update routine is called in a separate thread.</p>
<p>Warning: in Django, when a model instance is found via a relationship, the manager&#8217;s <code>get()</code> method is not called!  This is because these objects are accessed via a <code>django.db.models.fields.related.ManyRelatedManager</code>, rather than the model&#8217;s own manager.  If you wish to solve this without duplicating code, look into Django <code>signals</code>.</p>
<p>The problem is that this is not a simple side effect and the GIL will get in the way.  The solution is to do all of the necessary logic to determine if the object needs to be updated in the main thread.  Just before returning the response to the user, the update thread is started in Daemon mode.  That minimizes competition for the GIL.  The user will not get the updated version of the object on this page load, but the next user will.</p>
<p>The other alternative is to use <code>os.fork</code> or the <code>subprocess</code> module to launch the update routine in a separate process (with its own interpreter instance and its own GIL).  This sort of solution gets used a lot in PHP because of its lack of threads.  In Python, threads tend to be more useful and much less resource hungry.</p>
<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Submit article</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthreading-django%2F&amp;title=Threading+in+Django" rel="nofollow" title="Add to&nbsp;Del.icio.us"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/delicious.png" title="Add to&nbsp;Del.icio.us" alt="Add to&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthreading-django%2F&amp;title=Threading+in+Django" rel="nofollow" title="Add to&nbsp;digg"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/digg.png" title="Add to&nbsp;digg" alt="Add to&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.dzone.com/links/add.html?description=Threading+in+Django&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthreading-django%2F&amp;title=Threading+in+Django" rel="nofollow" title="Add to&nbsp;DZone"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/dzone.png" title="Add to&nbsp;DZone" alt="Add to&nbsp;DZone" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthreading-django%2F" rel="nofollow" title="Add to&nbsp;Facebook"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/facebook.png" title="Add to&nbsp;Facebook" alt="Add to&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthreading-django%2F&amp;title=Threading+in+Django" rel="nofollow" title="Add to&nbsp;reddit"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/reddit.png" title="Add to&nbsp;reddit" alt="Add to&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthreading-django%2F&amp;title=Threading+in+Django" rel="nofollow" title="Add to&nbsp;Stumble Upon"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Add to&nbsp;Stumble Upon" alt="Add to&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthreading-django%2F" rel="nofollow" title="Add to&nbsp;Technorati"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/technorati.png" title="Add to&nbsp;Technorati" alt="Add to&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Threading+in+Django+@+http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fthreading-django%2F" rel="nofollow" title="Add to&nbsp;Twitter"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/twitter.png" title="Add to&nbsp;Twitter" alt="Add to&nbsp;Twitter" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.artfulcode.net/articles/threading-django/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Multi-threading in Python</title>
		<link>http://www.artfulcode.net/articles/multi-threading-python/</link>
		<comments>http://www.artfulcode.net/articles/multi-threading-python/#comments</comments>
		<pubDate>Fri, 30 Nov 2007 16:02:00 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.artfulcode.net/articles/multi-threading-python/</guid>
		<description><![CDATA[Programming with threads is one of the more difficult tasks in programming. The Python threading and Queue modules make this significantly easier, but it still takes some deliberation to use threads in an efficient way. Python&#8217;s thread and threading libraries use POSIX threads. The threading library is the higher level of the two and is [...]]]></description>
			<content:encoded><![CDATA[<p>Programming with threads is one of the more difficult tasks in programming.  The Python threading and Queue modules make this significantly easier, but it still takes some deliberation to use threads in an efficient way.<span id="more-42"></span></p>
<p>Python&#8217;s thread and threading libraries use <a href="http://en.wikipedia.org/wiki/Posix_threads">POSIX threads</a>.  The threading library is the higher level of the two and is therefore the one to use in your typical programming tasks.  The Queue module provides a thread-safe mechanism for communicating between threads, like a combination list and <a href="http://en.wikipedia.org/wiki/Semaphore_(programming)">semaphore</a>.</p>
<p>POSIX threads are expensive, so it takes a little planning to know when to use them.  Generally, the best uses of threads are for multiple tasks that cause side effects but do not depend on the state of other threads, such as output.  An example of this is a program that writes out a large number of files with data from a database or a large data migration.  Here is the general template for a threading class that encapsulates the actions to be taken.</p>
<p>Assume we have around 500 XML documents to download off of a remote server (via HTTP).  Each is a large enough file that it warrants downloading several at a time.  The server and the network can take a fair load, but we don&#8217;t want to simulate a botnet attack or overload our local network connection, which would slow down each download to a crawl and drastically increase collisions and errors while downloading.  Let&#8217;s limit the number of files we download at once to 4.  We start off with a function to download the files:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">urllib</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> get_file<span style="color: black;">&#40;</span>url<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        f = <span style="color: #dc143c;">urllib</span>.<span style="color: black;">urlopen</span><span style="color: black;">&#40;</span>url<span style="color: black;">&#41;</span>
        contents = f.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        f.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> contents
     <span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">IOError</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Could not open document: %s&quot;</span> <span style="color: #66cc66;">%</span> url</pre></div></div>

<p>So much for error handling, but you get the idea.  Assuming our url is stored in a variable with the name url, to execute this function in another thread, we run:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">threading</span>
&nbsp;
<span style="color: #dc143c;">thread</span> = <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#40;</span>target=get_file, args=<span style="color: black;">&#40;</span>url,<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>We can make that a little simpler in two ways.  The object oriented way is to implement the threading.Thread class.  We would then put the code <code>get_file(url)</code> in our run() method.  This is useful for instances when the result of the function is required for later processing.  If the results are not needed, we can simplify using the functional programming method and utilize a partial application:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> functools <span style="color: #ff7700;font-weight:bold;">import</span> partial, <span style="color: #dc143c;">threading</span>
&nbsp;
<span style="color: #dc143c;">thread</span> = <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#40;</span>target=partial<span style="color: black;">&#40;</span>get_file, url<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>While that method is more fun, let&#8217;s use the OO method (no pun intended) since we want to do something with this data.  Remember, we are downloading the file and storing it as a string, rather than simply downloading the file to the local file system.  That implies we have more work to do after the download.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">urllib</span>, <span style="color: #dc143c;">threading</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> FileGetter<span style="color: black;">&#40;</span><span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, url<span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">url</span> = url
        <span style="color: #008000;">self</span>.<span style="color: black;">result</span> = <span style="color: #008000;">None</span>
        <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> get_result<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">result</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> run<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">try</span>:
            f = <span style="color: #dc143c;">urllib</span>.<span style="color: black;">urlopen</span><span style="color: black;">&#40;</span>url<span style="color: black;">&#41;</span>
            contents = f.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            f.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">result</span> = contents
         <span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">IOError</span>:
            <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Could not open document: %s&quot;</span> <span style="color: #66cc66;">%</span> url</pre></div></div>

<p>Now we have our Thread implementation.  Note that instantiating an instance of FileGetter does not cause the thread to start.  That is done with the start() method.  However, we don&#8217;t want all of the threads running at the same time, so we need to use the Queue module and a couple of helper functions to manage our list of files.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">threading</span>
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">Queue</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">Queue</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> get_files<span style="color: black;">&#40;</span>files<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> producer<span style="color: black;">&#40;</span>q, files<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">for</span> <span style="color: #008000;">file</span> <span style="color: #ff7700;font-weight:bold;">in</span> files:
            <span style="color: #dc143c;">thread</span> = FileGetter<span style="color: black;">&#40;</span><span style="color: #008000;">file</span><span style="color: black;">&#41;</span>
            <span style="color: #dc143c;">thread</span>.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            q.<span style="color: black;">put</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">thread</span>, <span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
&nbsp;
    finished = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> consumer<span style="color: black;">&#40;</span>q, total_files<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>finished<span style="color: black;">&#41;</span> <span style="color: #66cc66;">&amp;</span>lt<span style="color: #66cc66;">;</span> total_files:
            <span style="color: #dc143c;">thread</span> = q.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
            <span style="color: #dc143c;">thread</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            finished.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">thread</span>.<span style="color: black;">get_result</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    q = <span style="color: #dc143c;">Queue</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span>
    prod_thread = <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#40;</span>target=producer, args=<span style="color: black;">&#40;</span>q, files<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    cons_thread = <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#40;</span>target=consumer, args=<span style="color: black;">&#40;</span>q, <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>files<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    prod_thread.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    cons_thread.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    prod_thread.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    cons_thread.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Let&#8217;s take a look at what we did here.  The first function, producer, accepts the queue and the list of files.  For each file, it starts a new FileGetter thread.  The last line is significant.  We add the thread to the queue.  The second parameter, boolean True, tells the put() method to block until a slot is available.  Note that the thread stores before the blocking does.  This means that even if the queue is full, the thread will have started.  Because of this, we reduce our queue size to 3.</p>
<p>The second function, the consumer, reads items out of the queue, blocking until an item is available in the queue.  Then comes the important part, thread.join().  This causes the consumer to block until the thread completes its execution.  This line is what keeps the queue from emptying before the next thread has complete execution (and therefore starting more threads).  The consumer uses the module-level variable, finished, to store the results of each thread&#8217;s execution.</p>
<p>Last, we begin a thread for the producer and the consumer, start them, and then block until they have completed.  Here is the complete code:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">urllib</span>, <span style="color: #dc143c;">threading</span>
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">Queue</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">Queue</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> FileGetter<span style="color: black;">&#40;</span><span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, url<span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">url</span> = url
        <span style="color: #008000;">self</span>.<span style="color: black;">result</span> = <span style="color: #008000;">None</span>
        <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> get_result<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">result</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> run<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">try</span>:
            f = <span style="color: #dc143c;">urllib</span>.<span style="color: black;">urlopen</span><span style="color: black;">&#40;</span>url<span style="color: black;">&#41;</span>
            contents = f.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            f.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">result</span> = contents
         <span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">IOError</span>:
            <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Could not open document: %s&quot;</span> <span style="color: #66cc66;">%</span> url
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> get_files<span style="color: black;">&#40;</span>files<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> producer<span style="color: black;">&#40;</span>q, files<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">for</span> <span style="color: #008000;">file</span> <span style="color: #ff7700;font-weight:bold;">in</span> files:
            <span style="color: #dc143c;">thread</span> = FileGetter<span style="color: black;">&#40;</span><span style="color: #008000;">file</span><span style="color: black;">&#41;</span>
            <span style="color: #dc143c;">thread</span>.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            q.<span style="color: black;">put</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">thread</span>, <span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
&nbsp;
    finished = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> consumer<span style="color: black;">&#40;</span>q, total_files<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>finished<span style="color: black;">&#41;</span> <span style="color: #66cc66;">&amp;</span>lt<span style="color: #66cc66;">;</span> total_files:
            <span style="color: #dc143c;">thread</span> = q.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
            <span style="color: #dc143c;">thread</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            finished.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">thread</span>.<span style="color: black;">get_result</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    q = <span style="color: #dc143c;">Queue</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span>
    prod_thread = <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#40;</span>target=producer, args=<span style="color: black;">&#40;</span>q, files<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    cons_thread = <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#40;</span>target=consumer, args=<span style="color: black;">&#40;</span>q, <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>files<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    prod_thread.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    cons_thread.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    prod_thread.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    cons_thread.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Of course, this approach is not perfect.  A queue is FIFO &#8211; first in, first out.  If one of the threads currently executing finishes before the thread ahead of it, we lose efficiency in that now we only have three files downloading at a time.  However, the solution to that is a complex one and outside the scope of this article.</p>
<p><strong>Edit 02/19/2009:</strong> Fixed: FileGetter was not setting self.result in its run method. Thanks to tgray for pointing out the problem.</p>
<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Submit article</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmulti-threading-python%2F&amp;title=Multi-threading+in+Python" rel="nofollow" title="Add to&nbsp;Del.icio.us"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/delicious.png" title="Add to&nbsp;Del.icio.us" alt="Add to&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmulti-threading-python%2F&amp;title=Multi-threading+in+Python" rel="nofollow" title="Add to&nbsp;digg"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/digg.png" title="Add to&nbsp;digg" alt="Add to&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.dzone.com/links/add.html?description=Multi-threading+in+Python&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmulti-threading-python%2F&amp;title=Multi-threading+in+Python" rel="nofollow" title="Add to&nbsp;DZone"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/dzone.png" title="Add to&nbsp;DZone" alt="Add to&nbsp;DZone" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmulti-threading-python%2F" rel="nofollow" title="Add to&nbsp;Facebook"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/facebook.png" title="Add to&nbsp;Facebook" alt="Add to&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmulti-threading-python%2F&amp;title=Multi-threading+in+Python" rel="nofollow" title="Add to&nbsp;reddit"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/reddit.png" title="Add to&nbsp;reddit" alt="Add to&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmulti-threading-python%2F&amp;title=Multi-threading+in+Python" rel="nofollow" title="Add to&nbsp;Stumble Upon"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Add to&nbsp;Stumble Upon" alt="Add to&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmulti-threading-python%2F" rel="nofollow" title="Add to&nbsp;Technorati"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/technorati.png" title="Add to&nbsp;Technorati" alt="Add to&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Multi-threading+in+Python+@+http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fmulti-threading-python%2F" rel="nofollow" title="Add to&nbsp;Twitter"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/twitter.png" title="Add to&nbsp;Twitter" alt="Add to&nbsp;Twitter" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.artfulcode.net/articles/multi-threading-python/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Concurrency in newLISP</title>
		<link>http://www.artfulcode.net/articles/concurrency-newlisp/</link>
		<comments>http://www.artfulcode.net/articles/concurrency-newlisp/#comments</comments>
		<pubDate>Tue, 18 Sep 2007 14:25:00 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[newlisp]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.artfulcode.net/articles/concurrency-newlisp/</guid>
		<description><![CDATA[Threaded applications are considered to be so difficult to implement properly that programmers are often encouraged to avoid them unless absolutely necessary. This is because of the difficulty in synchronizing data between threads. There are several techniques to accomplish this. Typical solutions involve sharing an area of memory or a pipe (a channel that maps [...]]]></description>
			<content:encoded><![CDATA[<p>Threaded applications are considered to be so difficult to implement properly that programmers are often encouraged to avoid them unless absolutely necessary.  This is because of the difficulty in synchronizing data between threads.  There are several techniques to accomplish this.  Typical solutions involve sharing an area of memory or a pipe (a channel that maps one process&#8217; input channel to another&#8217;s output channel) in order to pass state between the two threads.  The difficulty with this solution is that trouble can arise if two threads attempt to write to that same area of shared memory at the same time.  One solution to this is to use a semaphore to signal threads that it is safe to write to shared memory.  Other solutions involve locking the memory with a mutex lock (mutually exclusive lock).<span id="more-46"></span></p>
<p>On unix-based systems, newLISP uses the operating system&#8217;s fork to create a child process.  State may be shared between two processes using either pipes or semaphores and shared memory.  It is slightly faster to use shared memory and semaphores, but more difficult to track and coordinate.  The process of forking the evaluation of an expression and accessing the result can be made easier with a couple functions to handle the messy business of coordinating access to shared memory.  The first, which we will call spawn (since I like Erlang), will fork a child process that will evaluate an expression, allocate a shared memory address, and create a semaphore to signal the process.</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>define-macro <span style="color: #66cc66;">&#40;</span>spawn<span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span>letn <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>expr <span style="color: #66cc66;">&#40;</span>args <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#40;</span>sem <span style="color: #66cc66;">&#40;</span>semaphore<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#40;</span>res <span style="color: #66cc66;">&#40;</span>share<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
         <span style="color: #66cc66;">&#40;</span>pid <span style="color: #66cc66;">&#40;</span>fork <span style="color: #66cc66;">&#40;</span>begin
                      <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>res-val <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">eval</span> expr<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
                        <span style="color: #66cc66;">&#40;</span>semaphore sem -<span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>
                        <span style="color: #66cc66;">&#40;</span>share res <span style="color: #66cc66;">&#40;</span>source 'res-val<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
                        <span style="color: #66cc66;">&#40;</span>exit<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">list</span> pid sem res<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Notice that block that the function is actually forking.  After evaluating the expression passed to spawn, it blocks by setting the semaphore to -1.  A positive value will cause it to unblock and evaluate (share res (source &#8216;res-val)).  (source) serializes the value of &#8216;res-val into a string (which will actually assign res-val when it is evaluated).  It then exits.  The function itself returns a list of the pid of the forked process, the semaphore and the shared memory address.</p>
<p>The spawn process can be used like so: <code>(setq proc (spawn (+ 3 6)))</code></p>
<p>Then we need a function that will read in the result from the spawned process.  It must block until the process is complete, and then attempt to read in the value from the shared memory.  Since we are using fork (which is unix-only, sorry!), we may as well clean up the shared memory afterward (which also only works on unix).</p>

<div class="wp_syntax"><div class="code"><pre class="lisp" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span>define <span style="color: #66cc66;">&#40;</span>receive proc <span style="color: #66cc66;">,</span> res-val serialized-result<span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">let</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>pid <span style="color: #66cc66;">&#40;</span>proc <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>sem <span style="color: #66cc66;">&#40;</span>proc <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#40;</span>res <span style="color: #66cc66;">&#40;</span>proc <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
       <span style="color: #66cc66;">&#40;</span>semaphore sem <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>
       <span style="color: #66cc66;">&#40;</span>wait-pid pid<span style="color: #66cc66;">&#41;</span>
       <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">setq</span> serialized-result <span style="color: #66cc66;">&#40;</span>share res<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
       <span style="color: #66cc66;">&#40;</span>share <span style="color: #b1b100;">nil</span> res<span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">; release shared memory</span>
       <span style="color: #66cc66;">&#40;</span>semaphore sem <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">; release semaphore</span>
       <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">catch</span> <span style="color: #66cc66;">&#40;</span>eval-string serialized-result<span style="color: #66cc66;">&#41;</span> 'res-val<span style="color: #66cc66;">&#41;</span>
           res-val 'invalid-result<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Here, we pass receive the result of the spawn function.  The value returned will be either the result of evaluating the expression passed to spawn or the symbol, &#8216;invalid-result.  This function first unblocks the spawned process, allowing it to store its result in shared memory, blocking until it completes.  It access the shared memory and then releases the shared memory address and semaphore.</p>
<p>The last statement is slightly tricky (if you are unfamiliar with newLISP error handling).  It attempts to evaluate the serialized result pulled from shared memory.  In the case of our example above, <code>(setq proc (spawn (+ 3 6)))</code>, this would expand to something like <code>(set 'res-val 9)</code>.  Remember that our statement above used res-val to store the result for serialization.  To avoid side effects, we declare res-val locally in our arguments (placing local variables after a comma in a lambda list is a newLISP convention to create local, nil variables; it is no different than declaring them as nil in a let statement or using the function local) and catch the result in it.  This is a bit redundant.  It would expand like, <code>(catch (eval-string (set 'res-val 9)) 'res-val)</code>, but the effect is the same and the overhead of an extra set is negligible.</p>
<p>These functions do not provide the power of Erlang&#8217;s concurrent syntax (especially since they use OS threads, which are inefficient, although this is mitigated somewhat by the size and speed of newLISP).  Instead, they achieve the desired result of simplifying the spawning of a child process (non-blocking) and accessing the result.  For many purposes, the complexity of formulating expressions in a concurrent fashion outweighs the gains (which sometimes are not so great) of concurrent programming.  By simplifying and automating the process, we negate that particular difficulty and can use the method that provides the most efficiency.</p>
<p>Well, on unix, anyway.</p>
<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Submit article</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fconcurrency-newlisp%2F&amp;title=Concurrency+in+newLISP" rel="nofollow" title="Add to&nbsp;Del.icio.us"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/delicious.png" title="Add to&nbsp;Del.icio.us" alt="Add to&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fconcurrency-newlisp%2F&amp;title=Concurrency+in+newLISP" rel="nofollow" title="Add to&nbsp;digg"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/digg.png" title="Add to&nbsp;digg" alt="Add to&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.dzone.com/links/add.html?description=Concurrency+in+newLISP&amp;url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fconcurrency-newlisp%2F&amp;title=Concurrency+in+newLISP" rel="nofollow" title="Add to&nbsp;DZone"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/dzone.png" title="Add to&nbsp;DZone" alt="Add to&nbsp;DZone" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fconcurrency-newlisp%2F" rel="nofollow" title="Add to&nbsp;Facebook"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/facebook.png" title="Add to&nbsp;Facebook" alt="Add to&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fconcurrency-newlisp%2F&amp;title=Concurrency+in+newLISP" rel="nofollow" title="Add to&nbsp;reddit"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/reddit.png" title="Add to&nbsp;reddit" alt="Add to&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fconcurrency-newlisp%2F&amp;title=Concurrency+in+newLISP" rel="nofollow" title="Add to&nbsp;Stumble Upon"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Add to&nbsp;Stumble Upon" alt="Add to&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fconcurrency-newlisp%2F" rel="nofollow" title="Add to&nbsp;Technorati"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/technorati.png" title="Add to&nbsp;Technorati" alt="Add to&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Concurrency+in+newLISP+@+http%3A%2F%2Fwww.artfulcode.net%2Farticles%2Fconcurrency-newlisp%2F" rel="nofollow" title="Add to&nbsp;Twitter"><img class="social_img" src="http://www.artfulcode.net/wp-content/plugins/social-bookmarks/images/twitter.png" title="Add to&nbsp;Twitter" alt="Add to&nbsp;Twitter" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.artfulcode.net/articles/concurrency-newlisp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

