<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">

<channel>
	<title>Just Software Solutions Blog</title> 
	<link>http://www.justsoftwaresolutions.co.uk/blog/</link> 
	<description>Software and Website Development</description> 

	<language>en-gb</language> 
	<copyright>Copyright 2007 Just Software Solutions Ltd.</copyright> 

	<managingEditor>Anthony Williams</managingEditor> 

	<webMaster>info@justsoftwaresolutions.co.uk</webMaster><item><title>Updated Implementation of Futures for C++</title><link>http://www.justsoftwaresolutions.co.uk/threading/updated-implementation-of-c++-futures.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/updated-implementation-of-c++-futures.html</guid><pubDate>Sun, 11 May 2008 10:51:17 +0100</pubDate><description><![CDATA[
<p>I have updated my <a href="http://www.justsoftwaresolutions.co.uk/threading/free-implementation-of-c++-futures.html">prototype futures library</a> implementation in light
of various comments received, and my own thoughts.</p>

<p>The new version is available for <a
href="http://www.justsoftwaresolutions.co.uk/files/n2561_futures_revised_20080511.zip">download</a>, again under the
<a href="http://www.boost.org/LICENSE_1_0.txt">Boost Software License</a>. It still needs to be compiled against the
<a href="http://svn.boost.org/svn/boost/trunk">Boost Subversion Trunk</a>, as it uses the Boost Exception library, which is not
available in an official boost release.</p>

<p>Sample usage can be seen in the test harness. The support for alternative allocators is still missing.

<h3>Changes</h3>

<ul> <li>I have removed  the <code>try_get</code>/<code>timed_get</code> functions, as they can be replaced with a
combination of <code>wait()</code> or <code>timed_wait()</code> and <code>get()</code>, and they don't work with
<code>unique_future&lt;R&amp;&gt;</code> or <code>unique_future&lt;void&gt;</code>.</li>

<li>I've also removed the <code>move()</code> functions on <code>unique_future</code>. Instead, <code>get()</code> returns an
rvalue-reference to allow moving in those types with move support. Yes, if you call <code>get()</code> twice on a movable type then
the second <code>get()</code> returns an empty shell of an object, but I don't really think that's a problem: if you want to call
<code>get()</code> multiple times, use a <code>shared_future</code>. I've implemented this with both rvalue-references and the
boost.thread move emulation, so you can have a <code>unique_future&lt;boost::thread&gt;</code> if necessary.
<code>test_unique_future_for_move_only_udt()</code> in test_futures.cpp shows this in action with a user-defined movable-only type
<code>X</code>.</li>

<li>Finally, I've added a <code>set_wait_callback()</code> function to both <code>promise</code> and
<code>packaged_task</code>. This allows for lazy-futures which don't actually run the operation to generate the value until the
value is needed: no threading required. It also allows for a thread pool to do task stealing if a pool thread waits for a task
that's not started yet.

<strong>The callbacks must be thread-safe</strong> as they are potentially called from many waiting threads simultaneously. At the
moment, I've specified the callbacks as taking a non-const reference to the <code>promise</code> or <code>packaged_task</code> for
which they are set, but I'm open to just making them be any callable function, and leaving it up to the user to call
<code>bind()</code> to do that.</li>

</ul>


<p>I've left the wait operations as <code>wait()</code> and <code>timed_wait()</code>, but I've had a suggestion to use
<code>wait()</code>/<code>wait_for()</code>/<code>wait_until()</code>, which I'm actively considering.</p>

<p>Please download this prototype, put it through its paces, and let me know what you think.</p>
<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/threading/">threading</a> /] <a href="http://www.justsoftwaresolutions.co.uk/threading/updated-implementation-of-c++-futures.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/futures" rel="tag">futures</a>,  <a href="http://technorati.com/tag/promise" rel="tag">promise</a>,  <a href="http://technorati.com/tag/threading" rel="tag">threading</a>,  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a>,  <a href="http://technorati.com/tag/n2561" rel="tag">n2561</a> <br>   <a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fupdated-implementation-of-c%2B%2B-futures.html&amp;title=Updated%20Implementation%20of%20Futures%20for%20C%2B%2B">Digg This</a> | <a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.justsoftwaresolutions.co.uk/threading/updated-implementation-of-c++-futures.html')+'&amp;title='+encodeURIComponent('Updated%20Implementation%20of%20Futures%20for%20C%2B%2B'), 'delicious','toolbar=no,width=700,height=400'); return false;">Save to del.icio.us</a> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fupdated-implementation-of-c%2B%2B-futures.html&amp;title=Updated%20Implementation%20of%20Futures%20for%20C%2B%2B"> Stumble It!</a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fupdated-implementation-of-c%2B%2B-futures.html&amp;title=Updated%20Implementation%20of%20Futures%20for%20C%2B%2B">Submit to Reddit</a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fupdated-implementation-of-c%2B%2B-futures.html&amp;title=Updated%20Implementation%20of%20Futures%20for%20C%2B%2B">Submit to DZone</a></small></p>]]></description></item><item><title>Free Implementation of Futures for C++ from N2561</title><link>http://www.justsoftwaresolutions.co.uk/threading/free-implementation-of-c++-futures.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/free-implementation-of-c++-futures.html</guid><pubDate>Mon, 05 May 2008 09:44:11 +0100</pubDate><description><![CDATA[
<p>I am happy to announce the release of a prototype futures library for C++ based on
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2561.html">N2561</a>. Packaged as a single 
<a href="http://www.justsoftwaresolutions.co.uk/files/n2561_future.hpp">header file</a> released under the
<a href="http://www.boost.org/LICENSE_1_0.txt">Boost Software License</a> it needs to be compiled against the
<a href="http://svn.boost.org/svn/boost/trunk">Boost Subversion Trunk</a>, as it uses the Boost Exception library, which is not
available in an official boost release.</p>

<p>Sample usage can be seen in the <a href="http://www.justsoftwaresolutions.co.uk/files/n2561_futures.zip">test harness</a>. There
is one feature missing, which is the support for alternative allocators. I intend to add such support in due course.</p>

<p>Please download this prototype, put it through its paces, and let me know what you think.</p>
<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/threading/">threading</a> /] <a href="http://www.justsoftwaresolutions.co.uk/threading/free-implementation-of-c++-futures.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/futures" rel="tag">futures</a>,  <a href="http://technorati.com/tag/promise" rel="tag">promise</a>,  <a href="http://technorati.com/tag/threading" rel="tag">threading</a>,  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a>,  <a href="http://technorati.com/tag/n2561" rel="tag">n2561</a> <br>   <a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffree-implementation-of-c%2B%2B-futures.html&amp;title=Free%20Implementation%20of%20Futures%20for%20C%2B%2B%20from%20N2561">Digg This</a> | <a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.justsoftwaresolutions.co.uk/threading/free-implementation-of-c++-futures.html')+'&amp;title='+encodeURIComponent('Free%20Implementation%20of%20Futures%20for%20C%2B%2B%20from%20N2561'), 'delicious','toolbar=no,width=700,height=400'); return false;">Save to del.icio.us</a> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffree-implementation-of-c%2B%2B-futures.html&amp;title=Free%20Implementation%20of%20Futures%20for%20C%2B%2B%20from%20N2561"> Stumble It!</a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffree-implementation-of-c%2B%2B-futures.html&amp;title=Free%20Implementation%20of%20Futures%20for%20C%2B%2B%20from%20N2561">Submit to Reddit</a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffree-implementation-of-c%2B%2B-futures.html&amp;title=Free%20Implementation%20of%20Futures%20for%20C%2B%2B%20from%20N2561">Submit to DZone</a></small></p>]]></description></item><item><title>Bug Found in Boost.Thread (with Fix): Flaw in Condition Variable on Windows</title><link>http://www.justsoftwaresolutions.co.uk/threading/bug_and_fix_in_boost_thread_condition_variable_for_windows.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/bug_and_fix_in_boost_thread_condition_variable_for_windows.html</guid><pubDate>Mon, 28 Apr 2008 08:39:38 +0100</pubDate><description><![CDATA[
<h3>There's a bug....</h3>

<p>First the bad news: shortly after <a href="http://www.boost.org">Boost</a>
1.35.0 was released, a couple of users reported experiencing problems using
<code>boost::condition_variable</code> on Windows: when they used
<code>notify_one()<\code>, sometimes their notifies disappeared, even when they
knew there was a waiting thread.</p>

<h3>... and now it's fixed</h3>

<p>Next, the good news: I've found and fixed the bug, and committed the fix to
the boost Subversion repository. If you can't update your boost implementation
to trunk, you can <a
href="http://svn.boost.org/svn/boost/trunk/boost/thread/win32/condition_variable.hpp">download
the new code</a> and replace
<code>boost/thread/win32/condition_variable.hpp</code> from the boost 1.35.0
distribution with the new version.</p>

<h3>What was it?</h3>

<p>For those of you interested in the details, this bug was in code related to
detecting (and preventing) spurious wakes. When a condition variable was
notified with <code>notify_one()</code>, the implementation was choosing one or
more threads to compete for the notify. One of these would get the notification
and return from <code>wait()</code>. Those that didn't get the notify were
supposed to resume waiting without returning from
<code>wait()</code>. Unfortunately, this left a potential gap where those
threads weren't waiting, so would miss any calls to <code>notify_one()</code>
that occurred before those threads resumed waiting.</p>

<p>The fix was to rewrite the wait/notify mechanism so this gap no longer
exists, by changing the way that waiting threads are counted.</p>
<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/threading/">threading</a> /] <a href="http://www.justsoftwaresolutions.co.uk/threading/bug_and_fix_in_boost_thread_condition_variable_for_windows.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/boost" rel="tag">boost</a>,  <a href="http://technorati.com/tag/thread" rel="tag">thread</a>,  <a href="http://technorati.com/tag/condition+variable" rel="tag">condition variable</a>,  <a href="http://technorati.com/tag/windows" rel="tag">windows</a> <br>   <a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fbug_and_fix_in_boost_thread_condition_variable_for_windows.html&amp;title=Bug%20Found%20in%20Boost.Thread%20%28with%20Fix%29%3A%20Flaw%20in%20Condition%20Variable%20on%20Windows">Digg This</a> | <a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.justsoftwaresolutions.co.uk/threading/bug_and_fix_in_boost_thread_condition_variable_for_windows.html')+'&amp;title='+encodeURIComponent('Bug%20Found%20in%20Boost.Thread%20%28with%20Fix%29%3A%20Flaw%20in%20Condition%20Variable%20on%20Windows'), 'delicious','toolbar=no,width=700,height=400'); return false;">Save to del.icio.us</a> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fbug_and_fix_in_boost_thread_condition_variable_for_windows.html&amp;title=Bug%20Found%20in%20Boost.Thread%20%28with%20Fix%29%3A%20Flaw%20in%20Condition%20Variable%20on%20Windows"> Stumble It!</a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fbug_and_fix_in_boost_thread_condition_variable_for_windows.html&amp;title=Bug%20Found%20in%20Boost.Thread%20%28with%20Fix%29%3A%20Flaw%20in%20Condition%20Variable%20on%20Windows">Submit to Reddit</a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fbug_and_fix_in_boost_thread_condition_variable_for_windows.html&amp;title=Bug%20Found%20in%20Boost.Thread%20%28with%20Fix%29%3A%20Flaw%20in%20Condition%20Variable%20on%20Windows">Submit to DZone</a></small></p>]]></description></item><item><title>The Future of Concurrency in C++: Slides from ACCU 2008</title><link>http://www.justsoftwaresolutions.co.uk/threading/future-of-concurrency-accu-2008-slides.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/future-of-concurrency-accu-2008-slides.html</guid><pubDate>Mon, 07 Apr 2008 13:14:13 +0100</pubDate><description><![CDATA[
<p>My presentation on <a href="http://www.justsoftwaresolutions.co.uk/news/future-of-concurrency-in-cplusplus-accu-2008.html">The
Future of Concurrency in C++</a> at <a href="http://www.accu.org/index.php/conferences/accu_conference_2008">ACCU 2008</a> last
Thursday went off without a hitch. I was pleased to find that my talk was well attended, and the audience had lots of worthwhile
questions &mdash; hopefully I answered them to everybody's satisfaction.</p>

<p>For those that didn't attend, or for those that did, but would like a reminder of what I said, here are the <a
href="/files/future_of_concurrency.pdf">slides from my presentation</a>.</p>


<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/threading/">threading</a> /] <a href="http://www.justsoftwaresolutions.co.uk/threading/future-of-concurrency-accu-2008-slides.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a>,  <a href="http://technorati.com/tag/multithreading" rel="tag">multithreading</a>,  <a href="http://technorati.com/tag/C++" rel="tag">C++</a>,  <a href="http://technorati.com/tag/ACCU" rel="tag">ACCU</a> <br>   <a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffuture-of-concurrency-accu-2008-slides.html&amp;title=The%20Future%20of%20Concurrency%20in%20C%2B%2B%3A%20Slides%20from%20ACCU%202008">Digg This</a> | <a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.justsoftwaresolutions.co.uk/threading/future-of-concurrency-accu-2008-slides.html')+'&amp;title='+encodeURIComponent('The%20Future%20of%20Concurrency%20in%20C%2B%2B%3A%20Slides%20from%20ACCU%202008'), 'delicious','toolbar=no,width=700,height=400'); return false;">Save to del.icio.us</a> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffuture-of-concurrency-accu-2008-slides.html&amp;title=The%20Future%20of%20Concurrency%20in%20C%2B%2B%3A%20Slides%20from%20ACCU%202008"> Stumble It!</a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffuture-of-concurrency-accu-2008-slides.html&amp;title=The%20Future%20of%20Concurrency%20in%20C%2B%2B%3A%20Slides%20from%20ACCU%202008">Submit to Reddit</a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffuture-of-concurrency-accu-2008-slides.html&amp;title=The%20Future%20of%20Concurrency%20in%20C%2B%2B%3A%20Slides%20from%20ACCU%202008">Submit to DZone</a></small></p>]]></description></item><item><title>Boost 1.35.0 has been Released!</title><link>http://www.justsoftwaresolutions.co.uk/news/boost-1-35-0-released.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/news/boost-1-35-0-released.html</guid><pubDate>Tue, 01 Apr 2008 14:32:15 +0100</pubDate><description><![CDATA[
<p>Verson 1.35.0 of the Boost libraries was released on Saturday. This release includes a major revision of the <a href="http://www.boost.org/doc/libs/1_35_0/doc/html/thread.html">Boost.Thread
library</a>, to bring it more in line with the C++0x Thread Library. There are many new libraries, and revisions to other libraries
too, see the full <a href="http://www.boost.org/users/download/version_1_35_0">Release Notes</a> for details, or just <a
href="http://sourceforge.net/project/showfiles.php?group_id=7586&amp;package_id=8041&amp;release_id=587936">Download</a> the release and
give it a try.</p>

<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/news/">news</a> /] <a href="http://www.justsoftwaresolutions.co.uk/news/boost-1-35-0-released.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/boost" rel="tag">boost</a> <br>   <a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fboost-1-35-0-released.html&amp;title=Boost%201.35.0%20has%20been%20Released%21">Digg This</a> | <a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.justsoftwaresolutions.co.uk/news/boost-1-35-0-released.html')+'&amp;title='+encodeURIComponent('Boost%201.35.0%20has%20been%20Released%21'), 'delicious','toolbar=no,width=700,height=400'); return false;">Save to del.icio.us</a> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fboost-1-35-0-released.html&amp;title=Boost%201.35.0%20has%20been%20Released%21"> Stumble It!</a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fboost-1-35-0-released.html&amp;title=Boost%201.35.0%20has%20been%20Released%21">Submit to Reddit</a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fboost-1-35-0-released.html&amp;title=Boost%201.35.0%20has%20been%20Released%21">Submit to DZone</a></small></p>]]></description></item><item><title>Optimizing Applications with Fixed-Point Arithmetic</title><link>http://www.justsoftwaresolutions.co.uk/news/optimizing-applications-with-fixed-point-arithmetic.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/news/optimizing-applications-with-fixed-point-arithmetic.html</guid><pubDate>Tue, 01 Apr 2008 14:29:36 +0100</pubDate><description><![CDATA[
<p>My latest article, <a href="http://www.ddj.com/cpp/207000448">Optimizing Math-intensive Applications with Fixed Point
Arithmetic</a> from the April 2008 issue of <a href="http://www.ddj.com">Dr Dobb's Journal</a> is now available online. (I
originally had "Maths-intensive" in the title, being English, but they dropped the "s", being American).</p>

<p>In the article, I describe the fixed-point techniques I used to vastly improve the performance of an application using sines,
cosines and exponentials without hardware floating point support.</p>

<p>The source code referenced in the article can be downloaded from <a href="/files/fixed_source.zip">here</a>. It is released under
the <a href="http://www.boost.org/LICENSE_1_0.txt">Boost Software License</a>.</p>
<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/news/">news</a> /] <a href="http://www.justsoftwaresolutions.co.uk/news/optimizing-applications-with-fixed-point-arithmetic.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/optimization" rel="tag">optimization</a>,  <a href="http://technorati.com/tag/fixed-point" rel="tag">fixed-point</a>,  <a href="http://technorati.com/tag/maths" rel="tag">maths</a> <br>   <a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Foptimizing-applications-with-fixed-point-arithmetic.html&amp;title=Optimizing%20Applications%20with%20Fixed-Point%20Arithmetic">Digg This</a> | <a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.justsoftwaresolutions.co.uk/news/optimizing-applications-with-fixed-point-arithmetic.html')+'&amp;title='+encodeURIComponent('Optimizing%20Applications%20with%20Fixed-Point%20Arithmetic'), 'delicious','toolbar=no,width=700,height=400'); return false;">Save to del.icio.us</a> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Foptimizing-applications-with-fixed-point-arithmetic.html&amp;title=Optimizing%20Applications%20with%20Fixed-Point%20Arithmetic"> Stumble It!</a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Foptimizing-applications-with-fixed-point-arithmetic.html&amp;title=Optimizing%20Applications%20with%20Fixed-Point%20Arithmetic">Submit to Reddit</a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Foptimizing-applications-with-fixed-point-arithmetic.html&amp;title=Optimizing%20Applications%20with%20Fixed-Point%20Arithmetic">Submit to DZone</a></small></p>]]></description></item><item><title>Futures and Tasks in C++0x</title><link>http://www.justsoftwaresolutions.co.uk/threading/futures-and-tasks-in-c++0x.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/futures-and-tasks-in-c++0x.html</guid><pubDate>Thu, 27 Mar 2008 14:20:18 +0000</pubDate><description><![CDATA[
<p>I had resigned myself to <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2276.html">Thread Pools and
Futures</a> being punted to TR2 rather than C++0x, but it seems there is potential for some movement on this issue. At the meeting
of WG21 in Kona, Hawaii in October 2007 it was agreed to include asynchronous future values in C++0x, whilst excluding thread pools
and task launching.</p>

<p>Detlef Vollman has rekindled the effort, and drafted <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2561.html">N2561: An Asynchronous Future Value</a> with myself and
Howard Hinnant, based on a discussion including other members of the Standards Committee. This paper proposes four templates:
<code>unique_future</code> and <code>shared_future</code>, which are the asynchronous values themselves, and
<code>packaged_task</code> and <code>promise</code>, which provide ways of setting the asynchronous values.</p>

<h3>Asynchronous future values</h3>

<p><code>unique_future</code> is very much like <code>unique_ptr</code>: it represents exclusive ownership of the value. Ownership
of a (future) value can be moved between <code>unique_future</code> instances, but no two <code>unique_future</code> instances can
refer to the same asynchronous value. Once the value is ready for retrieval, it is <em>moved</em> out of the internal storage
buffer: this allows for use with move-only types such as <code>std::ifstream</code>.</p>

<p>Similarly, <code>shared_future</code> is very much like <code>shared_ptr</code>: multiple instances can refer to the same
(future) value, and <code>shared_future</code> instances can be copied around. In order to reduce surprises with this usage (with
one thread moving the value through one instance at the same time as another tries to move it through another instance), the stored
value can only be accessed via <code>const</code> reference, so must be copied out, or accessed in place.</p>

<h3>Storing the future values as the return value from a function</h3>

<p>The simplest way to calculate a future value is with a <code>packaged_task&lt;T&gt;</code>. Much like <code>std::function&lt;T()&gt;</code>, this
encapsulates a callable object or function, for invoking at a later time. However, whereas <code>std::function</code> returns the
result directly to the caller, <code>packaged_task</code> stores the result in a future.</p>

<pre class="listing">
    extern int some_function();
    std::packaged_task&lt;int&gt; task(some_function);
    std::unique_future&lt;int&gt; result=task.get_future();

    // later on, some thread does
    task();
    // and "result" is now ready
</pre>

<h3>Making a <code>promise</code> to provide a future value</h3>

<p>The other way to store a value to be picked up with a <code>unique_future</code> or <code>shared_future</code> is to use a
<code>promise</code>, and then explicitly set the value by calling the <code>set_value()</code> member function.</p>

<pre class="listing">
    std::promise&lt;int&gt; my_promise;
    std::unique_future&lt;int&gt; result=my_promise.get_future();

    // later on, some thread does
    my_promise.set_value(42);
    // and "result" is now ready.
</pre>

<h3>Exceptional returns</h3>

<p>Futures also support storing exceptions: when you try and retrieve the value, if there is a stored exception, that exception is
thrown rather than the value being retrieved. With a <code>packaged_task</code>, an exception gets stored if the wrapped function
throws an exception when it is invoked, and with a <code>promise</code>, you can explicitly store an exception with the
<code>set_exception()</code> member function.</p>

<h3>Feedback</h3>

<p>As the paper says, this is not a finished proposal: it is a basis for further discussion. <a
href="mailto:anthony@justsoftwaresolutions.co.uk">Let me know</a> if you have any comments.</p>

<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/threading/">threading</a> /] <a href="http://www.justsoftwaresolutions.co.uk/threading/futures-and-tasks-in-c++0x.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/threading" rel="tag">threading</a>,  <a href="http://technorati.com/tag/futures" rel="tag">futures</a>,  <a href="http://technorati.com/tag/asynchronous+values" rel="tag">asynchronous values</a>,  <a href="http://technorati.com/tag/C++0x" rel="tag">C++0x</a>,  <a href="http://technorati.com/tag/wg21" rel="tag">wg21</a> <br>   <a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffutures-and-tasks-in-c%2B%2B0x.html&amp;title=Futures%20and%20Tasks%20in%20C%2B%2B0x">Digg This</a> | <a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.justsoftwaresolutions.co.uk/threading/futures-and-tasks-in-c++0x.html')+'&amp;title='+encodeURIComponent('Futures%20and%20Tasks%20in%20C%2B%2B0x'), 'delicious','toolbar=no,width=700,height=400'); return false;">Save to del.icio.us</a> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffutures-and-tasks-in-c%2B%2B0x.html&amp;title=Futures%20and%20Tasks%20in%20C%2B%2B0x"> Stumble It!</a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffutures-and-tasks-in-c%2B%2B0x.html&amp;title=Futures%20and%20Tasks%20in%20C%2B%2B0x">Submit to Reddit</a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Ffutures-and-tasks-in-c%2B%2B0x.html&amp;title=Futures%20and%20Tasks%20in%20C%2B%2B0x">Submit to DZone</a></small></p>]]></description></item><item><title>Thread Interruption in the Boost Thread Library</title><link>http://www.justsoftwaresolutions.co.uk/threading/thread-interruption-in-boost-thread-library.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/thread-interruption-in-boost-thread-library.html</guid><pubDate>Tue, 11 Mar 2008 13:22:00 +0000</pubDate><description><![CDATA[
<p>One of the new features introduced in the upcoming 1.35.0 release of the <a href="http://www.boost.org">boost</a> thread library is
support for <em>interruption</em> of a running thread. Similar to the Java and .NET interruption support, this allows for one thread
to request another thread to stop at the next <em>interruption point</em>. This is the only way to explicitly request a thread to
terminate that is directly supported by the Boost Thread library, though users can manually implement cooperative interruption if
required.</p>

<p>Interrupting a thread in this way is much less dangerous than brute-force tactics such as
<code>TerminateThread()</code>, as such tactics can leave broken invariants and leak resources. If a thread is killed using a
brute-force method and it was holding any locks, this can also potentially lead to deadlock when another thread tries to acquire
those locks at some future point. Interruption is also easier and more reliable than rolling your own cooperative termination scheme
using mutexes, flags, condition variables, or some other synchronization mechanism, since it is part of the library.</p>

<h3>Interrupting a Thread</h3>

<p>A running thread can be interrupted by calling the <code>interrupt()</code> member function on the corresponding
<code>boost::thread</code> object. If the thread doesn't have a <code>boost::thread</code> object (e.g the initial thread of the
application), then it cannot be interrupted.</p>

<p>Calling <code>interrupt()</code> just sets a flag in the thread management structure for that thread and returns: it doesn't wait
for the thread to actually be interrupted. This is important, because a thread can only be interrupted at one of the predefined
<em>interruption points</em>, and it might be that a thread never executes an interruption point, so never sees the
request. Currently, the interruption points are:</p>

<ul>
<li><code>boost::thread::join()</code></li>
<li><code>boost::thread::timed_join()</code></li>
<li><code>boost::condition_variable::wait()</code></li>
<li><code>boost::condition_variable::timed_wait()</code></li>
<li><code>boost::condition_variable_any::wait()</code></li>
<li><code>boost::condition_variable_any::timed_wait()</code></li>
<li><code>boost::this_thread::sleep()</code></li>
<li><code>boost::this_thread::interruption_point()</code></li>
</ul>

<p>When a thread reaches one of these interruption points, if interruption is enabled for that thread then it checks its
interruption flag. If the flag is set, then it is cleared, and a <code>boost::thread_interrupted</code> exception is thrown. If the
thread is already blocked on a call to one of the interruption points with interruption enabled when <code>interrupt()</code> is
called, then the thread will wake in order to throw the <code>boost::thread_interrupted</code> exception.</p>

<h3>Catching an Interruption</h3>

<p><code>boost::thread_interrupted</code> is just a normal exception, so it can be caught, just like any other exception. This is
why the "interrupted" flag is cleared when the exception is thrown &mdash; if a thread catches and handles the interruption, it is
perfectly acceptable to interrupt it again. This can be used, for example, when a worker thread that is processing a series of
independent tasks &mdash; if the current task is interrupted, the worker can handle the interruption and discard the task, and move
onto the next task, which can then in turn be interrupted. It also allows the thread to catch the exception and terminate itself by
other means, such as returning error codes, or translating the exception to pass through module boundaries.</p>

<h3>Disabling Interruptions</h3>

<p>Sometimes it is necessary to avoid being interrupted for a particular section of code, such as in a destructor where an exception
has the potential to cause immediate process termination. This is done by constructing an instance of
<code>boost::this_thread::disable_interruption</code>. Objects of this class disable interruption for the thread that created them on
construction, and restore the interruption state to whatever it was before on destruction:</p>

<pre class="listing">
    void f()
    {
        // interruption enabled here
        {
            boost::this_thread::disable_interruption di;
            // interruption disabled
            {
                boost::this_thread::disable_interruption di2;
                // interruption still disabled
            } // di2 destroyed, interruption state restored
            // interruption still disabled
        } // di destroyed, interruption state restored
        // interruption now enabled
    }
</pre>

<p>The effects of an instance of <code>boost::this_thread::disable_interruption</code> can be temporarily reversed by constructing
an instance of <code>boost::this_thread::restore_interruption</code>, passing in the
<code>boost::this_thread::disable_interruption</code> object in question. This will restore the interruption state to what it was
when the <code>boost::this_thread::disable_interruption</code> object was constructed, and then disable interruption again when the
<code>boost::this_thread::restore_interruption</code> object is destroyed:</p>

<pre class="listing">
    void g()
    {
        // interruption enabled here
        {
            boost::this_thread::disable_interruption di;
            // interruption disabled
            {
                boost::this_thread::restore_interruption ri(di);
                // interruption now enabled
            } // ri destroyed, interruption disabled again
            {
                boost::this_thread::disable_interruption di2;
                // interruption disabled
                {
                    boost::this_thread::restore_interruption ri2(di2);
                    // interruption still disabled
                    // as it was disabled when di2 constructed
                } // ri2 destroyed, interruption still disabled
            } //di2 destroyed, interruption still disabled
        } // di destroyed, interruption state restored
        // interruption now enabled
    }
</pre>

<p><code>boost::this_thread::disable_interruption</code> and <code>boost::this_thread::restore_interruption</code> cannot be moved
or copied, and they are the only way of enabling and disabling interruption. This ensures that the interruption state is correctly
restored when the scope is exited (whether normally, or by an exception), and that you cannot enable interruptions in the middle of
an interruption-disabled block unless you're in full control of the code, and have access to the
<code>boost::this_thread::disable_interruption</code> instance.</p>

<p>At any point, the interruption state for the current thread can be queried by calling
<code>boost::this_thread::interruption_enabled()</code>.</p>

<h3>Cooperative Interruption</h3>

<p>As well as the interruption points on blocking operations such as <code>sleep()</code> and <code>join()</code>, there is one
interruption point explicitly designed to allow interruption at a user-designated point in the
code. <code>boost::this_thread::interruption_point()</code> does nothing except check for an interruption, and can therefore be used
in long-running code that doesn't execute any other interruption points, in order to allow for cooperative interruption. Just like
the other interruption points, <code>interruption_point()</code> respects the interruption enabled state, and does nothing if
interruption is disabled for the current thread.</p>

<h3>Interruption is Not Cancellation</h3>

<p>On POSIX platforms, threads can be cancelled rather than killed, by calling <code>pthread_cancel()</code>. This is similar to interruption, but is a separate mechanism, with different behaviour. In particular,
cancellation cannot be stopped once it is started: whereas interruption just throws an exception, once a cancellation request has
been acknowledged the thread is effectively dead. <code>pthread_cancel()</code> does not always execute destructors either (though
it does on some platforms), as it is primarily a C interface &mdash; if you want to clean up your resources when a thread is
cancelled, you need to use <code>pthread_cleanup_push()</code> to register a cleanup handler. The advantage here is that
<code>pthread_cleanup_push()</code> works in C stack frames, whereas exceptions don't play nicely in C: on some platforms it will
crash your program for an exception to propagate into a C stack frame.</p>

<p>For portable code, I recommend interruption over cancellation. It's supported on all platforms that can use the Boost Thread
library, and it works well with C++ code &mdash; it's just another exception, so all your destructors and catch blocks work just
fine.</p>

<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/threading/">threading</a> /] <a href="http://www.justsoftwaresolutions.co.uk/threading/thread-interruption-in-boost-thread-library.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/thread" rel="tag">thread</a>,  <a href="http://technorati.com/tag/boost" rel="tag">boost</a>,  <a href="http://technorati.com/tag/interruption" rel="tag">interruption</a>,  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a>,  <a href="http://technorati.com/tag/cancellation" rel="tag">cancellation</a>,  <a href="http://technorati.com/tag/multi-threading" rel="tag">multi-threading</a> <br>   <a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-interruption-in-boost-thread-library.html&amp;title=Thread%20Interruption%20in%20the%20Boost%20Thread%20Library">Digg This</a> | <a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.justsoftwaresolutions.co.uk/threading/thread-interruption-in-boost-thread-library.html')+'&amp;title='+encodeURIComponent('Thread%20Interruption%20in%20the%20Boost%20Thread%20Library'), 'delicious','toolbar=no,width=700,height=400'); return false;">Save to del.icio.us</a> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-interruption-in-boost-thread-library.html&amp;title=Thread%20Interruption%20in%20the%20Boost%20Thread%20Library"> Stumble It!</a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-interruption-in-boost-thread-library.html&amp;title=Thread%20Interruption%20in%20the%20Boost%20Thread%20Library">Submit to Reddit</a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-interruption-in-boost-thread-library.html&amp;title=Thread%20Interruption%20in%20the%20Boost%20Thread%20Library">Submit to DZone</a></small></p>]]></description></item><item><title>Acquiring Multiple Locks Without Deadlock</title><link>http://www.justsoftwaresolutions.co.uk/threading/acquiring-multiple-locks-without-deadlock.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/acquiring-multiple-locks-without-deadlock.html</guid><pubDate>Mon, 03 Mar 2008 11:38:48 +0000</pubDate><description><![CDATA[
<p>In a software system with lots of fine-grained mutexes, it can sometimes be necessary to acquire locks on more than one mutex
together in order to perform some operation. If this is not done with care, then there is the possibility of deadlock, as multiple
threads may lock the same mutexes in a different order. It is for this reason that the thread library coming with C++0x will include
a <code>lock()</code> function for locking multiple mutexes together: this article describes the implementation details behind such
a function.</p>

<h3>Choose the lock order by role</h3>

<p>The easiest way to deal with this is to always lock the mutexes in the same order. This is especially easy if the order can be
hard-coded, and some uses naturally lend themselves towards this choice. For example, if the mutexes protect objects with different
roles, it is relatively easy to always lock the mutex protecting one set of data before locking the other one. In such a situation,
<strong>Lock hierarchies</strong> can be used to enforce the ordering &mdash; with a lock hierarchy, a thread cannot acquire a lock
on a mutex with a higher <em>hierarchy level</em> than any mutexes currently locked by that thread.</p>

<p>If it is not possible to decide a-priori which mutex to lock first, such as when the mutexes are associated with the same sort of
data, then a more complicated policy must be applied.</p>

<h3>Choose the lock order by address</h3>

<p>The simplest technique in these cases is to always lock the mutexes in ascending order of address (examples use the types and
functions from the upcoming 1.35 release of <a href="http://www.boost.org">Boost</a>), like this:

<pre class="listing">
void lock(boost::mutex&amp; m1,boost::mutex&amp; m2)
{
    if(&amp;m1&lt;&amp;m2)
    {
        m1.lock();
        m2.lock();
    }
    else
    {
        m2.lock();
        m1.lock();
    }
}
</pre>

<p>This works for small numbers of mutexes, provided this policy is maintained throughout the application, but if several mutexes
must be locked together, then calculating the ordering can get complicated, and potentially inefficient. It also requires that the
mutexes are all of the same type. Since there are many possible mutex and lock types that an application might choose to use, this
is a notable disadvantage, as the function must be written afresh for each possible combination.</p>

<h3>Order mutexes "naturally", with try-and-back-off</h3>

<p>If the mutexes cannot be ordered by address (for whatever reason), then an alternative scheme must be found. One such scheme is
to use a try-and-back-off algorithm: try and lock each mutex in turn; if any cannot be locked, unlock the others and start
again. The simplest implementation for 3 mutexes looks like this:

<pre class="listing">
void lock(boost::mutex&amp; m1,boost::mutex&amp; m2,boost::mutex&amp; m3)
{
    do
    {
        m1.lock();
        if(m2.try_lock())
        {
            if(m3.try_lock())
            {
                return;
            }
            m2.unlock();
        }
        m1.unlock();
    }
    while(true);
}
</pre>

<h3>Wait for the failed mutex</h3>

<p>The big problem with this scheme is that it always locks the mutexes in the same order. If <code>m1</code> and <code>m2</code>
are currently free, but <code>m3</code> is locked by another thread, then this thread will repeatedly lock <code>m1</code> and
<code>m2</code>, fail to lock <code>m3</code> and unlock <code>m1</code> and <code>m2</code>. This just wastes CPU cycles for no
gain. Instead, what we want to do is <em>block</em> waiting for <code>m3</code>, and try to acquire the others only when
<code>m3</code> has been successfully locked by this thread. For three mutexes, a first attempt looks like this:

<pre class="scrolling-listing">
void lock(boost::mutex&amp; m1,boost::mutex&amp; m2,boost::mutex&amp; m3)
{
    unsigned lock_first=0;
    while(true)
    {
        switch(lock_first)
        {
        case 0:
            m1.lock();
            if(m2.try_lock())
            {
                if(m3.try_lock())
                    return;
                lock_first=2;
                m2.unlock();
            }
            else
            {
                lock_first=1;
            }
            m1.unlock();
            break;
        case 1:
            m2.lock();
            if(m3.try_lock())
            {
                if(m1.try_lock())
                    return;
                lock_first=0;
                m3.unlock();
            }
            else
            {
                lock_first=2;
            }
            m2.unlock();
            break;
        case 2:
            m3.lock();
            if(m1.try_lock())
            {
                if(m2.try_lock())
                    return;
                lock_first=1;
                m1.unlock();
            }
            else
            {
                lock_first=0;
            }
            m3.unlock();
            break;
        }
    }
}
</pre>

<h3>Simplicity and Robustness</h3>

<p>This code is very long-winded, with all the duplication between the <code>case</code> blocks. Also, it assumes that the mutexes
are all <code>boost::mutex</code>, which is overly restrictive. Finally, it assumes that the <code>try_lock</code> calls don't throw
exceptions. Whilst this is true for the Boost mutexes, it is not required to be true in general, so a more robust implementation
that allows the mutex type to be supplied as a template parameter will ensure that any exceptions thrown will leave all the mutexes
unlocked: the <code>unique_lock</code> template will help with that by providing RAII locking. Taking all this into account leaves
us with the following:

<pre class="scrolling-listing">
template&lt;typename MutexType1,typename MutexType2,typename MutexType3&gt;
unsigned lock_helper(MutexType1&amp; m1,MutexType2&amp; m2,MutexType3&amp; m3)
{
    boost::unique_lock&lt;MutexType1&gt; l1(m1);
    boost::unique_lock&lt;MutexType2&gt; l2(m2,boost::try_to_lock);
    if(!l2)
    {
        return 1;
    }
    if(!m3.try_lock())
    {
        return 2;
    }
    l2.release();
    l1.release();
    return 0;
}

template&lt;typename MutexType1,typename MutexType2,typename MutexType3&gt;
void lock(MutexType1&amp; m1,MutexType2&amp; m2,MutexType3&amp; m3)
{
    unsigned lock_first=0;
    while(true)
    {
        switch(lock_first)
        {
        case 0:
            lock_first=lock_helper(m1,m2,m3);
            if(!lock_first)
                return;
            break;
        case 1:
            lock_first=lock_helper(m2,m3,m1);
            if(!lock_first)
                return;
            lock_first=(lock_first+1)%3;
            break;
        case 2:
            lock_first=lock_helper(m3,m1,m2);
            if(!lock_first)
                return;
            lock_first=(lock_first+2)%3;
            break;
        }
    }
}
</pre>

<p>This code is simultaneously shorter, simpler and more general than the previous implementation, and is robust in the face of
exceptions. The <code>lock_helper</code> function locks the first mutex, and then tries to lock the other two in turn. If either of
the <code>try_lock</code>s fail, then all currently-locked mutexes are unlocked, and it returns the index of the mutex than couldn't
be locked. On success, the <code>release</code> members of the <code>unique_lock</code> instances are called to release ownership of
the locks, and thus stop them automatically unlocking the mutexes during destruction, and <code>0</code> is returned. The outer
<code>lock</code> function is just a simple wrapper around <code>lock_helper</code> that chooses the order of the mutexes so that
the one that failed to lock last time is tried first.</p>

<h3>Extending to more mutexes</h3>

<p>This scheme can also be easily extended to handle more mutexes, though the code gets unavoidably longer, since there are more
cases to handle &mdash; this is where the C++0x variadic templates will really come into their own. Here's the code for locking 5
mutexes together:

<pre class="scrolling-listing">
template&lt;typename MutexType1,typename MutexType2,typename MutexType3,
         typename MutexType4,typename MutexType5&gt;
unsigned lock_helper(MutexType1&amp; m1,MutexType2&amp; m2,MutexType3&amp; m3,
                     MutexType4&amp; m4,MutexType5&amp; m5)
{
    boost::unique_lock&lt;MutexType1&gt; l1(m1);
    boost::unique_lock&lt;MutexType2&gt; l2(m2,boost::try_to_lock);
    if(!l2)
    {
        return 1;
    }
    boost::unique_lock&lt;MutexType3&gt; l3(m3,boost::try_to_lock);
    if(!l3)
    {
        return 2;
    }
    boost::unique_lock&lt;MutexType4&gt; l2(m4,boost::try_to_lock);
    if(!l4)
    {
        return 3;
    }
    if(!m5.try_lock())
    {
        return 4;
    }
    l4.release();
    l3.release();
    l2.release();
    l1.release();
    return 0;
}

template&lt;typename MutexType1,typename MutexType2,typename MutexType3,
         typename MutexType4,typename MutexType5&gt;
void lock(MutexType1&amp; m1,MutexType2&amp; m2,MutexType3&amp; m3,
          MutexType4&amp; m4,MutexType5&amp; m5)
{
    unsigned const lock_count=5;
    unsigned lock_first=0;
    while(true)
    {
        switch(lock_first)
        {
        case 0:
            lock_first=lock_helper(m1,m2,m3,m4,m5);
            if(!lock_first)
                return;
            break;
        case 1:
            lock_first=lock_helper(m2,m3,m4,m5,m1);
            if(!lock_first)
                return;
            lock_first=(lock_first+1)%lock_count;
            break;
        case 2:
            lock_first=lock_helper(m3,m4,m5,m1,m2);
            if(!lock_first)
                return;
            lock_first=(lock_first+2)%lock_count;
            break;
        case 3:
            lock_first=lock_helper(m4,m5,m1,m2,m3);
            if(!lock_first)
                return;
            lock_first=(lock_first+3)%lock_count;
            break;
        case 4:
            lock_first=lock_helper(m5,m1,m2,m3,m4);
            if(!lock_first)
                return;
            lock_first=(lock_first+4)%lock_count;
            break;
        }
    }
}
</pre>

<h3>Final Code</h3>

<p>The <a href="http://www.justsoftwaresolutions.co.uk/files/multiple_locks.hpp">final code for acquiring multiple locks</a>
provides <code>try_lock</code> and <code>lock</code> functions for 2 to 5 mutexes. Though the <code>try_lock</code> functions are
relatively straight-forward, their existence makes the <code>lock_helper</code> functions slightly simpler, as they can just defer
to the appropriate overload of <code>try_lock</code> to cover all the mutexes beyond the first one.</p>
<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/threading/">threading</a> /] <a href="http://www.justsoftwaresolutions.co.uk/threading/acquiring-multiple-locks-without-deadlock.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/threading" rel="tag">threading</a>,  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a>,  <a href="http://technorati.com/tag/mutexes" rel="tag">mutexes</a>,  <a href="http://technorati.com/tag/locks" rel="tag">locks</a> <br>   <a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Facquiring-multiple-locks-without-deadlock.html&amp;title=Acquiring%20Multiple%20Locks%20Without%20Deadlock">Digg This</a> | <a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.justsoftwaresolutions.co.uk/threading/acquiring-multiple-locks-without-deadlock.html')+'&amp;title='+encodeURIComponent('Acquiring%20Multiple%20Locks%20Without%20Deadlock'), 'delicious','toolbar=no,width=700,height=400'); return false;">Save to del.icio.us</a> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Facquiring-multiple-locks-without-deadlock.html&amp;title=Acquiring%20Multiple%20Locks%20Without%20Deadlock"> Stumble It!</a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Facquiring-multiple-locks-without-deadlock.html&amp;title=Acquiring%20Multiple%20Locks%20Without%20Deadlock">Submit to Reddit</a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Facquiring-multiple-locks-without-deadlock.html&amp;title=Acquiring%20Multiple%20Locks%20Without%20Deadlock">Submit to DZone</a></small></p>]]></description></item><item><title>Thread Library Now in C++0x Working Draft</title><link>http://www.justsoftwaresolutions.co.uk/threading/thread-library-now-in-C++0x-working-draft.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/thread-library-now-in-C++0x-working-draft.html</guid><pubDate>Mon, 11 Feb 2008 09:12:43 +0000</pubDate><description><![CDATA[
<p>The latest proposal for the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2497.html">C++ standard thread
library</a> has finally made it into the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2521.pdf">C++0x working
draft</a>.</p>

<p>Woohoo!</p>

<p>There will undoubtedly be minor changes as feedback comes in to the committee, but this is the first real look at what C++0x
thread support will entail, as approved by the whole committee. The working draft also includes the new <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2429.htm">C++0x memory model</a>, and <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2427.html">atomic types and operations</a>. This means that for the
first time, C++ programs will legitimately be able to spawn threads without immediately straying into undefined behaviour. Not only
that, but the memory model has been very carefully thought out, so it should be possible to write even low-level stuff such as
lock-free containers in Standard C++.</p>


<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/threading/">threading</a> /] <a href="http://www.justsoftwaresolutions.co.uk/threading/thread-library-now-in-C++0x-working-draft.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/threading" rel="tag">threading</a>,  <a href="http://technorati.com/tag/C++" rel="tag">C++</a>,  <a href="http://technorati.com/tag/C++0x" rel="tag">C++0x</a>,  <a href="http://technorati.com/tag/news" rel="tag">news</a> <br>   <a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-library-now-in-C%2B%2B0x-working-draft.html&amp;title=Thread%20Library%20Now%20in%20C%2B%2B0x%20Working%20Draft">Digg This</a> | <a href="http://del.icio.us/post" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.justsoftwaresolutions.co.uk/threading/thread-library-now-in-C++0x-working-draft.html')+'&amp;title='+encodeURIComponent('Thread%20Library%20Now%20in%20C%2B%2B0x%20Working%20Draft'), 'delicious','toolbar=no,width=700,height=400'); return false;">Save to del.icio.us</a> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-library-now-in-C%2B%2B0x-working-draft.html&amp;title=Thread%20Library%20Now%20in%20C%2B%2B0x%20Working%20Draft"> Stumble It!</a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-library-now-in-C%2B%2B0x-working-draft.html&amp;title=Thread%20Library%20Now%20in%20C%2B%2B0x%20Working%20Draft">Submit to Reddit</a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-library-now-in-C%2B%2B0x-working-draft.html&amp;title=Thread%20Library%20Now%20in%20C%2B%2B0x%20Working%20Draft">Submit to DZone</a></small></p>]]></description></item></channel></rss>