<?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-2010 Just Software Solutions Ltd.</copyright> 

	<managingEditor>Anthony Williams</managingEditor> 

	<webMaster>info@justsoftwaresolutions.co.uk</webMaster><item><title>Happy New Year 2012</title><link>http://www.justsoftwaresolutions.co.uk/news/happy-new-year-2012.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/news/happy-new-year-2012.html</guid><pubDate>Tue, 10 Jan 2012 11:15:22 +0000</pubDate><description><![CDATA[
<p>Now the post-holidays rush is over, I'd like to wish you all a Happy New Year!</p>

<p>2011 was another good year for me. Sales of
  <code>Just::Thread</code>,
  my <a href="http://www.stdthread.co.uk">implementation of the C++11
  thread library</a> continue to grow,
  and <a href="http://www.stdthread.co.uk/book">my book</a> is finally
  in typesetting, and nearly ready for printing. We had hoped to get
  it done by the end of 2011, but last-minute corrections scuppered
  that. It should now be done relatively quickly.</p>

<p>It's also been a big year for the C++ community: C++11 is now an
official <a
href="http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=50372">ISO
standard</a>. This is the culmination of many years of hard work from
a huge number of people, so it's good to see it finally done.</p>

<h3>Popular articles</h3>

<p>As is my custom, here's a list of the 10 most popular articles and
  blog entries from the Just Software Solutions website in 2011.</p>

<ol>

<li><a
href="http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html">Implementing
a Thread-Safe Queue using Condition Variables</a><br> A description of
the issues around writing a thread-safe queue, with code.</li>

<li><a
href="http://www.justsoftwaresolutions.co.uk/articles/css_menus.html">Implementing
drop-down menus in pure CSS (no JavaScript)</a><br>How to implement
drop-down menus in CSS in a cross-browser fashion (with a teensy bit
of JavaScript for IE).</li>

<li><a href="http://www.justsoftwaresolutions.co.uk/general/importing-windows-into-virtualbox.html">Importing
an Existing Windows XP Installation into VirtualBox</a><br>This
article describes how I recovered the hard disk of a dead laptop to
run as a VM
under <a href="http://www.virtualbox.org">VirtualBox</a>.</li>

<li><a href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-1-starting-threads.html">Multithreading
in C++0x part 1: Starting Threads</a><br>This is the first part of my
  series on the new C++11 thread library. Links to the remaining
  parts are at the end of the article.</li>

<li><a href="http://www.justsoftwaresolutions.co.uk/threading/thread-safe-copy-constructors.html">Thread-Safe
    Copy and Move Constructors</a><br>This is a guest post by Michael
    Spertus on writing copy and move constructors for objects with
  internal locks.</li>

<li><a href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-2-function-objects-and-arguments.html">Multithreading
  in C++0x part 2: Starting Threads with Function Objects and
  Arguments</a><br>This is the second part of my series on the new
  C++11 thread library, which covers using callable objects when
  starting threads, and passing arguments to the thread function.</li>

<li><a
href="http://www.justsoftwaresolutions.co.uk/articles/intrototemplates.pdf">Introduction
to C++ Templates</a><br>My basic introduction to C++ templates.</li>

<li><a href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-8-futures-and-promises.html">Multithreading
  in C++0x part 8: Futures, Promises and Asynchronous Function
  Calls</a><br>This is the eighth part of my series on the new C++11
  thread library, which covers the "futures" mechanism for passing
  data between threads.</li>

<li><a
href="http://www.justsoftwaresolutions.co.uk/threading/thread-interruption-in-boost-thread-library.html">Thread
Interruption in the Boost Thread Library</a><br>A description of the
thread interruption feature of the Boost Thread library.</li>


<li><a
href="http://www.justsoftwaresolutions.co.uk/threading/deadlock_detection_with_just_thread.html">Deadlock
    Detection with just::thread</a><br>This article describes how to
  use the special deadlock-detection mode of
  our <a href="http://www.stdthread.co.uk"><code>just::thread</code>
    C++11 thread library</a> to locate the cause of deadlocks.</li>


</ol>

<h3>What's coming in 2012?</h3>

<p>Will 2012 be even better than 2011? I hope so. As I already
  mentioned,  <a
  href="http://www.stdthread.co.uk/book">my book</a> will finally be
  printed, which will be a big relief for me.</p>

<p>What are you looking forward to in 2011?</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/happy-new-year-2012.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/popular" rel="tag">popular</a>,  <a href="http://technorati.com/tag/articles" rel="tag">articles</a> <br>  <div class="g-plusone" data-size="large" data-annotation="none" data-href="http://www.justsoftwaresolutions.co.uk/news/happy-new-year-2012.html"></div> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fhappy-new-year-2012.html&amp;title=Happy%20New%20Year%202012"> Stumble It! <img src="http://www.justsoftwaresolutions.co.uk/images/stumbleupon.png" width=16 height=16 class="sm" alt="stumbleupon logo"></a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fhappy-new-year-2012.html&amp;title=Happy%20New%20Year%202012">Submit to Reddit <img src="http://www.justsoftwaresolutions.co.uk/images/reddit.png" width=16 height=16 class="sm" alt="reddit logo"></a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fhappy-new-year-2012.html&amp;title=Happy%20New%20Year%202012">Submit to DZone <img src="http://www.justsoftwaresolutions.co.uk/images/dzone.png" width=16 height=16 class="sm" alt="dzone logo"></a></small></p><p><a href="http://www.justsoftwaresolutions.co.uk/news/happy-new-year-2012.html#makecomment">Comment on this post</a></p><p>Follow me on <a href="http://twitter.com/a_williams">Twitter</a></p>]]></description></item><item><title>Memories of Learning C</title><link>http://www.justsoftwaresolutions.co.uk/general/memories_of_learning_c.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/general/memories_of_learning_c.html</guid><pubDate>Mon, 17 Oct 2011 10:15:38 +0000</pubDate><description><![CDATA[
<p><a href="http://herbsutter.com/2011/10/16/your-first-c-program/">Herb
  Sutter's latest blog entry</a> invites us to share our memories of
  our first C program, in tribute to Dennis Ritchie. I can't remember
  what my first C program was, but I thought I'd write about my
  memories of learning C.</p>

<p>I studied Physics at college, and there was very little programming
  taught as part of the course. That didn't bother me though; I'd
  taught myself to program up until then, and I wasn't going to stop
  now. The big benefit I got from computing at college was access to
  the internet, and access to C and C++ compilers. I could program in
  BASIC, Pascal and a couple of forms of assembly language, and I'd
  eagerly read Stan Lippman's C++ Primer and written out (on paper!)
  some C++ code, but I hadn't yet had a C++ compiler to try out my
  programs on.</p>

<p>I wrote several C++ programs before I even considered writing a
  plain C program, but I probably typed in and compiled the
  classic <code>printf("hello world\n");</code> C program to check
  everything was working before I compiled any C++.</p>
 
<h3>Usenet</h3>

<p>My strongest memories about learning C are about learning from
  usenet. Though I had access to C compilers at college, access to
  experts was not so readily available unless you were studying
  computing. With access to the internet, I didn't need local experts
  though &mdash; usenet provided access to experts from across the
  world. I read comp.lang.c and comp.lang.c++ avidly, and taught
  myself both languages together. The usenet community was invaluable
  to me. The wealth of knowledge that people had, and their
  willingness to share with newbies was something I really
  appreciated.</p>

<p>I remember struggling over file handling, and getting the arguments
to <code>scanf</code> right; I remember puzzling over the poor
performance of a program and having someone kindly point out that my
code was doing <code>malloc</code> and <code>free</code> calls in a
tight loop. Though I tend to answer more questions than I ask these
days, I still hang out on newgroups such as comp.lang.c++ today. It
seems that for many
people <a href="http://stackoverflow.com">StackOverflow</a> has
replaced usenet as the place to go for help, but the old-style
newsgroups are still valuable.</p>

<h3>Ubiquity</h3>

<p>Back then, C++ compilers were in their infancy. Templates didn't
  work on every compiler, there was no STL, and many platforms didn't
  have a working C++ compiler at all. I consequently wrote a lot of C
  &mdash; every platform had a C compiler, and my C code would work on
  the college PCs, my PC (when I saved up enough to buy one), the
  University's Unix machine, and the Physics department
  workstations. The same could not be said for C++.</p>

<p>The ubiquity of C is something I still appreciate today, and this
  is only possible because Dennis Ritchie designed his language to be
  portable to multiple platforms. Though "implementation defined"
  behaviour can be frustrating when the implementation defines it a
  different way to how you would like, it is this that enables the
  portability. You want to write code for a DSP that only handles
  32-bit data? Fine:
  make <code>char</code>, <code>short</code>, <code>int</code>
  and <code>long</code> all 32-bits. What if your machine has 9-bit
  bytes? No problem: just make <code>char</code> 9 bits, and
  everything else a convenient multiple of that. </p>

<p>C is the basic lingua-franca of the computing world. It is a
  "portable assembly language". These days I use C++ where I can
  because it allows a higher level of abstraction, and easier
  expression of intent without compromising on the performance you'd
  get with plain C, but it's not as portable, and wouldn't be possible
  without C.</p>

<p>The computing world owes a lot to Dennis Ritchie.</p>
<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/general/">general</a> /] <a href="http://www.justsoftwaresolutions.co.uk/general/memories_of_learning_c.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/C" rel="tag">C</a>,  <a href="http://technorati.com/tag/nostalgia" rel="tag">nostalgia</a> <br>  <div class="g-plusone" data-size="large" data-annotation="none" data-href="http://www.justsoftwaresolutions.co.uk/general/memories_of_learning_c.html"></div> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fgeneral%2Fmemories_of_learning_c.html&amp;title=Memories%20of%20Learning%20C"> Stumble It! <img src="http://www.justsoftwaresolutions.co.uk/images/stumbleupon.png" width=16 height=16 class="sm" alt="stumbleupon logo"></a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fgeneral%2Fmemories_of_learning_c.html&amp;title=Memories%20of%20Learning%20C">Submit to Reddit <img src="http://www.justsoftwaresolutions.co.uk/images/reddit.png" width=16 height=16 class="sm" alt="reddit logo"></a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fgeneral%2Fmemories_of_learning_c.html&amp;title=Memories%20of%20Learning%20C">Submit to DZone <img src="http://www.justsoftwaresolutions.co.uk/images/dzone.png" width=16 height=16 class="sm" alt="dzone logo"></a></small></p><p><a href="http://www.justsoftwaresolutions.co.uk/general/memories_of_learning_c.html#makecomment">Comment on this post</a></p><p>Follow me on <a href="http://twitter.com/a_williams">Twitter</a></p>]]></description></item><item><title>Computer Education</title><link>http://www.justsoftwaresolutions.co.uk/general/computer-education.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/general/computer-education.html</guid><pubDate>Wed, 12 Oct 2011 07:58:00 +0000</pubDate><description><![CDATA[
<p>Andrew Hague's post
on <a href="http://altdevblogaday.com/2011/10/12/computer-education-in-great-britain/">Computer
Education in Britain</a> touches on something I've been discussing
with my wife recently.</p>

<h3>The travesty of ICT</h3>

<p>Our children do not get taught anything at school about how
computers work, or how to program them, and are unlikely to. Andrew
says he found that "the study of computer science for British children
ends at about age 11." This doesn't tally with my experience of
primary schools &mdash; they are <strong>never</strong> taught any
computer science. Local secondary schools are proud of their ICT
suites, with office programs and image editing programs galore, but
not a single class on the basics of computers and programming.</p>

<p>Part of the problem is the complexity of modern computers. Whereas
the computers we grew up with (the Dragon 32, BBC Micro, ZX Spectrum,
Commodore 64, etc.) were simple beasts, and booted into a programming
environment (BASIC), modern computers are complex beasts with a swish
graphical OS with no native programming environment. Yes, you can use
Javascript in a browser, or the macro language in office programs, but
it's not the same. PCs do not invite programming the same way that the
older computers did, and you have to go out of your way to provide a
basic programming environment.</p>

<p>Schools could overcome this hurdle, and provide programming
environments, but they don't. Instead they teach everyone how to use
the latest versions of office programs, despite the fact that next
year's release will have a different UI, and different
capabilities. Yes, children need to be computer-savvy, due to the
prevalence of computers in everyday life, but they don't need to be
experts in using word processors. Rather, they should be taught how
  <strong>to learn to use</strong> the programs, the things that are
common about them (e.g. menus), how to get help (the help menu,
Google), and so forth, and then taught about how computers work. Yes,
use a word processor for writing the occasional thing in English, or
use a spreadsheet for doing some data analysis in Geography, but the
"computing" lessons should be about programming and how computers work
at the basic level, rather than how to use popular software.</p>

<p>I think this lack of teaching about the basics of computing has a
  wider effect, as well as the lack of new programmers. The computer
  is something that people don't understand, but which they rely
  on. This can give people a sense of powerlessness, especially when
  it does something unexpected. I've had to help people who've been
  all in a panic because they "lost their work".  It didn't appear in
  the list that was presented in the "open file" dialog, so it was
  "lost". Somehow they had saved it in a different directory, and
  their lack of understanding about the file system meant they didn't
  know how to find it, and panicked &mdash; the computer that they
  relied on had "lost" their important work. Teaching about the basics
  of modern operating systems (rather than the specifics of the
  software package being used) would have alleviated this fear.</p>

<h3>Addressing the Problem</h3>

<p>So, what is to be done? Firstly, as programming parents we can
  teach our children about computers and programming, which is
  something that my wife and I have started doing. But beyond that, we
  need to make the schools, colleges and government aware of the
  issues.</p>

<p>Andrew points to
  the <a href="http://www.computingatschool.org.uk/">Computing at
  School</a> working group and
  the <a href="http://www.theregister.co.uk/2011/10/04/gov_it_skills/">Behind
  the Screen</a> project, both of which seem promising. However,
  without support these projects will fizzle, and our children will
  continue to be taught how to use office software rather than
  computing principles.</p>
<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/general/">general</a> /] <a href="http://www.justsoftwaresolutions.co.uk/general/computer-education.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/computing" rel="tag">computing</a>,  <a href="http://technorati.com/tag/education" rel="tag">education</a>,  <a href="http://technorati.com/tag/schools" rel="tag">schools</a> <br>  <div class="g-plusone" data-size="large" data-annotation="none" data-href="http://www.justsoftwaresolutions.co.uk/general/computer-education.html"></div> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fgeneral%2Fcomputer-education.html&amp;title=Computer%20Education"> Stumble It! <img src="http://www.justsoftwaresolutions.co.uk/images/stumbleupon.png" width=16 height=16 class="sm" alt="stumbleupon logo"></a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fgeneral%2Fcomputer-education.html&amp;title=Computer%20Education">Submit to Reddit <img src="http://www.justsoftwaresolutions.co.uk/images/reddit.png" width=16 height=16 class="sm" alt="reddit logo"></a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fgeneral%2Fcomputer-education.html&amp;title=Computer%20Education">Submit to DZone <img src="http://www.justsoftwaresolutions.co.uk/images/dzone.png" width=16 height=16 class="sm" alt="dzone logo"></a></small></p><p><a href="http://www.justsoftwaresolutions.co.uk/general/computer-education.html#makecomment">Comment on this post</a></p><p>Follow me on <a href="http://twitter.com/a_williams">Twitter</a></p>]]></description></item><item><title>just::thread C++0x Thread Library V1.7.0 Released</title><link>http://www.justsoftwaresolutions.co.uk/news/just-thread-v1.7.0-released.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/news/just-thread-v1.7.0-released.html</guid><pubDate>Wed, 05 Oct 2011 07:36:52 +0000</pubDate><description><![CDATA[
<p>I am pleased to announce that version 1.7.0
  of <a href="http://www.stdthread.co.uk"><code>just::thread</code></a>,
  our <a href="http://www.stdthread.co.uk">C++0x Thread Library</a>
  has just been released.</p>

<p>This release adds official support for gcc v4.4 on Centos 6, so
Just::Thread is now supported on Centos, Fedora, Ubuntu and Debian
Linux distributions, as well as Microsoft Windows and Apple MacOSX.</p>

<p>The main change with this release is an enhancement to
  the <code><a href="http://www.stdthread.co.uk/doc/headers/future/async.html">std::async</a></code>
  implementation. With this enhanced scheduler, the default launch
  policy (<code>std::launch::async | std::launch::deferred</code>)
  will defer forcing a decision until either enough resources become
  available to schedule the task as <code>std::launch::async</code>,
  or the task is forced to be scheduled
  as <code>std::launch:deferred</code> by a call to a waiting function
  (<code>get()</code>, <code>wait()</code>, <code>wait_for()</code> or
  <code>wait_until()</code>). This will allow more tasks to be
  scheduled as <code>std::launch::async</code> overall, and allow your
  application to make better use of the available hardware
  concurrency.</p>

<p>The implementation of recursive mutexes has been overhauled,
  leading to much faster lock and unlock times than in previous
  releases.</p>

<p>This release also provides debugger visualizers for Microsoft
  Visual Studio, to better show the state of Just::Thread objects such
  as futures. This will provide greater insight into the state of your
  program, and allow easier debugging.</p>

<p><strong><a href="http://www.stdthread.co.uk/order.html">Purchase your
copy</a> and get started with the C++0x thread library now.</strong></p>

<p>As usual, existing customers are entitled to a free upgrade to V1.7.0
from all earlier versions.</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/just-thread-v1.7.0-released.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/multithreading" rel="tag">multithreading</a>,  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a>,  <a href="http://technorati.com/tag/C++0x" rel="tag">C++0x</a> <br>  <div class="g-plusone" data-size="large" data-annotation="none" data-href="http://www.justsoftwaresolutions.co.uk/news/just-thread-v1.7.0-released.html"></div> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fjust-thread-v1.7.0-released.html&amp;title=just%3A%3Athread%20C%2B%2B0x%20Thread%20Library%20V1.7.0%20Released"> Stumble It! <img src="http://www.justsoftwaresolutions.co.uk/images/stumbleupon.png" width=16 height=16 class="sm" alt="stumbleupon logo"></a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fjust-thread-v1.7.0-released.html&amp;title=just%3A%3Athread%20C%2B%2B0x%20Thread%20Library%20V1.7.0%20Released">Submit to Reddit <img src="http://www.justsoftwaresolutions.co.uk/images/reddit.png" width=16 height=16 class="sm" alt="reddit logo"></a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fjust-thread-v1.7.0-released.html&amp;title=just%3A%3Athread%20C%2B%2B0x%20Thread%20Library%20V1.7.0%20Released">Submit to DZone <img src="http://www.justsoftwaresolutions.co.uk/images/dzone.png" width=16 height=16 class="sm" alt="dzone logo"></a></small></p><p><a href="http://www.justsoftwaresolutions.co.uk/news/just-thread-v1.7.0-released.html#makecomment">Comment on this post</a></p><p>Follow me on <a href="http://twitter.com/a_williams">Twitter</a></p>]]></description></item><item><title>Thread-Safe Copy and Move Constructors</title><link>http://www.justsoftwaresolutions.co.uk/threading/thread-safe-copy-constructors.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/thread-safe-copy-constructors.html</guid><pubDate>Wed, 17 Aug 2011 22:06:56 +0000</pubDate><description><![CDATA[
<p><strong>This is a guest post by Michael Spertus. Michael is a
    Distinguished Engineer at Symantec. He is also a C++ Standards
    Committee member and teaches the graduate C++ sequence at the
    University of Chicago. He can be contacted
    at <a href="mailto:mike_spertus@symantec.com">mike_spertus@symantec.com</a>.</strong></p>

<hr>

<p>This guest column discusses writing thread-safe constructors. As we will
see, this is more difficult than it seems. Fortunately, we will also
see that C++11 offers a very pretty solution to this problem that nicely
  illustrates the synergy of the new  features introduced in
  C++11.</p>

<h4>The problem</h4>

<p>If you have a class that supports locking of objects to serialize
      access to a given object, you probably want the class' copy
      constructor and move constructor (if it has one) to lock the
      source object to get a consistent snapshot of the source object so
      the destination object isn't messed up if the source changes in
      the middle of the copy or move. </p>

<p>This isn't nearly as easy as it sounds. In the following class, a
      mutex is used to try to enforce the invariant that <code>i_squared</code>
      should always be the square of <code>i</code>.</p>
<pre class="listing">
class A {
public:  A(_i = 0) { set(_i); }
  set(int _i) {
    std::lock_guard&lt;std::mutex&gt; lock(mtx);
    i = _i;
    i_squared = i*i;
  }
  ...
private:
  std::mutex mtx;
  int i;
  int i_squared;
};</pre>

<p>Unfortunately, the default copy constructor doesn't acquire the
mutex, so in code like the following, <code>f</code>
      can copy a "half set" version of <code>a</code>
      if another thread modifies <code>a</code>
  at the same time.</p>

<pre class="listing">void f(A &amp;a) 
{
  A a2 = a;
  ...
}</pre>

<h4>First attempt</h4>

<p>A naive attempt is to acquire the lock in the constructor body just like in a thread-safe
  method.</p>

<pre class="listing">class A {
public:
  A(const A &amp;a) : i(a.i), i_squared(a.i_squared) {
    std::lock_guard&lt;std::mutex&gt; lock(a.mtx); // Too late!
  }
  ...
};</pre>

<p>Unfortunately, this fares no better
      as <code>i</code> and <code>i_squared</code> are
  copied before we acquire the lock.</p>

<h4>Second attempt</h4>

<p>One approach would be to simply not lock in the copy constructor at all 
  and just manually lock objects you want to copy:</p>

<pre class="listing">void f(A &amp;a)
{
  std::lock_guard&lt;std::mutex&gt;
  lock(a.mtx);
  A a2 = a;
  ...
}</pre>

<p>This approach deserves careful consideration. For classes which 
are not usually shared between threads or which need locking granularity
at a different level than their internal operations, managing locks
within the class can be an antipattern. This concern was a primary reason 
why C++11 does not have an equivalent to the <code>SynchronizedCollection</code>
wrapper found in Java and C#. For example, synchronized
collections make it easy to inadvertently loop through a collection believing
your code is thread-safe even though the collection could change between
individual operations on the collection during the loop. Of course, if
we decide not to have <code>A</code>'s copy constructor lock, then <code>A::set()</code>
  should not lock either.</p>

<p>Still, it remains a very common and useful pattern for classes designed for shared
use to have all their internal operations acquire the
lock (i.e.,  
<a href="http://en.wikipedia.org/wiki/Monitor_%28synchronization%29">monitors/synchronized classes</a>).
If <code>A</code> is a synchronized class that locks its methods internally, it would
be very confusing and prone to intermittent errors to still have to manually acquire
the 
lock whenever an object is copied or moved. Also, generic 
code, which doesn't know about <code>A::mtx</code> is unlikely to work
properly.</p>

<h4>Third attempt</h4>

<p>One thing we can do is dispense with member initialization lists in
  constructors altogether</p>

<pre class="listing">class A {
public:
  A(const A &amp;a) {
    std::lock_guard&lt;std::mutex&gt; lock(a.mtx);
    i = a.i;
    i_squared = a.i_squared;
  }
  ...
};</pre>

<p>This solution is awkward at best if any bases or members don't
      have default constructors, have reference type, or are const. It
      also seems unfair to have to pay an efficiency penalty (for
      constructing and assigning separately) just because there is no
      place to put the lock. In practice, I also suspect intermittent
      errors will creep into large code bases as programmers carelessly add a
      base or member initializer to the constructor. Finally, it just isn't very satisfying to
      have to just discard core parts of constructor syntax just because
  your class is synchronized.</p>

<h4>Fourth attempt</h4>

<p>Anthony Williams has suggested implementing serialized classes using a wrapper
  class like:</p>

<pre class="listing">struct PrivateBaseForA
{
     int i;
     int i_squared;
};

class A: private PrivateBaseForA
{
   mutable std::mutex mtx;
public:
   A(int _i = 0) { set(_i); }
   void set(int _i) {
     std::lock_guard&lt;std::mutex&gt; lock(mtx);
     i = _i;
     i_squared = _i*_i;
   }
   A(const A& other):
     PrivateBaseForA((std::lock_guard&lt;std::mutex&gt;(other.mtx),other))
   {}
};</pre>

<p>Anthony makes slick use of double-parens to use the comma operator. If you
wanted to avoid this, you could have <code>PrivateBaseForA</code>'s constructor take a lock.
</p>

<p>Again, this is not yet a very satisfying solution because
writing a wrapper class for every synchronized class just to get
  a properly locked copy constructor is clumsy and intrusive.</p>

<h4>Finally, the C++11 approach</h4>

<p>Fortunately, C++11 offers a nice solution that really illustrates
      how beautifully and powerfully the features of C++11 work
      together.  C++11
      supports <a href="http://www2.research.att.com/~bs/C++0xFAQ.html#delegating-ctor">forwarding
      one constructor to another</a>, which gives us an opportunity to
      grab the mutex before any copying or moving takes place:</p>

<pre class="listing">class A {
private:
  A(const A &amp;a, const std::lock_guard&lt;std::mutex&gt; &amp;)
   : i(a.i), i_squared(a.i_squared) {}
public:
  A(const A &amp;a) : A(a, std::lock_guard&lt;std::mutex&gt;(a.mtx)) {}
  ...
};</pre>

<p>This solution locks the entire constructor, protects against races
resulting from forgetting the manual lock, works with generic code,
  and doesn't require the creation of artificial wrapper classes.</p>

<p>While I think this is clearly the preferred solution, it is not perfect. To begin with, it
is more obscure and guru-like than I would wish for such a common situation. Secondly, constructor
forwarding is not yet implemented by any major C++ compiler (although
the recently approved standard should change that soon). Finally, we lose the
      benefit of compiler generated copy constructors. If we added an
      i_cubed field to A that also needed to be kept consistent with i,
      we might forget to update the private constructor.
      Perhaps this will be a further opportunity for the next C++ standard (C++1y?). In the
      meantime, C++11 provides a powerful new solution to the everyday
  problem of writing thread-safe copy and move constructors.</p>

<p>One final note is to mention that although this article focused on
copy constructors, everything applies equally to move constructors.
Indeed, any constructor that needs to acquire any lock whatsoever
  (e.g., a database lock) for its entire duration can apply these techniques.</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-safe-copy-constructors.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/multithreading" rel="tag">multithreading</a>,  <a href="http://technorati.com/tag/copying" rel="tag">copying</a> <br>  <div class="g-plusone" data-size="large" data-annotation="none" data-href="http://www.justsoftwaresolutions.co.uk/threading/thread-safe-copy-constructors.html"></div> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-safe-copy-constructors.html&amp;title=Thread-Safe%20Copy%20and%20Move%20Constructors"> Stumble It! <img src="http://www.justsoftwaresolutions.co.uk/images/stumbleupon.png" width=16 height=16 class="sm" alt="stumbleupon logo"></a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-safe-copy-constructors.html&amp;title=Thread-Safe%20Copy%20and%20Move%20Constructors">Submit to Reddit <img src="http://www.justsoftwaresolutions.co.uk/images/reddit.png" width=16 height=16 class="sm" alt="reddit logo"></a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fthread-safe-copy-constructors.html&amp;title=Thread-Safe%20Copy%20and%20Move%20Constructors">Submit to DZone <img src="http://www.justsoftwaresolutions.co.uk/images/dzone.png" width=16 height=16 class="sm" alt="dzone logo"></a></small></p><p><a href="http://www.justsoftwaresolutions.co.uk/threading/thread-safe-copy-constructors.html#makecomment">Comment on this post</a></p><p>Follow me on <a href="http://twitter.com/a_williams">Twitter</a></p>]]></description></item><item><title>Simplify Code by Encapsulating Locks</title><link>http://www.justsoftwaresolutions.co.uk/threading/simplify_code_by_encapsulating_locks.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/simplify_code_by_encapsulating_locks.html</guid><pubDate>Wed, 15 Jun 2011 09:13:54 +0000</pubDate><description><![CDATA[
<p>Over on the Future Chips blog, Aater Suleman argues
that <a href="http://www.futurechips.org/software-for-hardware-guys/quick-tip-why-while1-can-make-parallel-code-better.html"><code>while(1)</code>
can make parallel code better</a>. Whilst I agree that the code
using <code>while(1)</code> is simpler than the original in terms of
analysing the lock patterns, it achieves this by testing the logical
condition inside the <code>while</code> and
using <code>break</code>. This is additional, unnecessary,
complexity.</p>

<p>What is wanted instead is a way of encapsulating the locking, so
  that the loop logic is simple, and yet the lock logic is also
  clear.</p>

<p>Here is the original code from the blog post:</p>

<pre class="listing">
lock_acquire(lock);
while(check_condition()){
  lock_release(lock);
  //do any actual work in the iteration - Thanks to Caleb for this comment
  lock_acquire(lock);
}

lock_release(lock);
</pre>

<p>The implication here is that <code>check_condition()</code> must be
  called with the lock held, but the lock need not be held for the
  actual iteration work. The code thus acquires and releases the mutex
  in two places, which is unnecessary duplication, and a potential
  source of errors &mdash; if the loop exits early then the lock may
  be released twice, for example.</p>

<p>Rather than moving the condition check into the loop to avoid this
  duplication, a better solution is to move the lock acquisition and
  release into the condition check:</p>

<pre class="listing">
bool atomic_check_condition()
{
  lock_acquire(lock);
  bool result=check_condition();
  lock_release(lock);
  return result;
}

while(atomic_check_condition()){
  //do any actual work in the iteration - Thanks to Caleb for this comment
}
</pre>

<p>This gives us the best of both worlds: the lock is now held only
  across the <code>check_condition()</code> call, but the logic of
  the <code>while</code> loop is still clear.</p>

<p>If you're programming in C++, then the C++0x library allows us to
  make <code>atomic_check_condition()</code> even simpler by
  using <code>lock_guard</code> as in the code below, but extracting
  the function is always an improvement.</p>

<pre class="listing">
bool atomic_check_condition()
{
  std::lock_guard&lt;mutex_type&gt; guard(lock);
  return check_condition();
}
</pre>
<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/simplify_code_by_encapsulating_locks.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/multithreading" rel="tag">multithreading</a>,  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a>,  <a href="http://technorati.com/tag/locks" rel="tag">locks</a> <br>  <div class="g-plusone" data-size="large" data-annotation="none" data-href="http://www.justsoftwaresolutions.co.uk/threading/simplify_code_by_encapsulating_locks.html"></div> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fsimplify_code_by_encapsulating_locks.html&amp;title=Simplify%20Code%20by%20Encapsulating%20Locks"> Stumble It! <img src="http://www.justsoftwaresolutions.co.uk/images/stumbleupon.png" width=16 height=16 class="sm" alt="stumbleupon logo"></a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fsimplify_code_by_encapsulating_locks.html&amp;title=Simplify%20Code%20by%20Encapsulating%20Locks">Submit to Reddit <img src="http://www.justsoftwaresolutions.co.uk/images/reddit.png" width=16 height=16 class="sm" alt="reddit logo"></a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fsimplify_code_by_encapsulating_locks.html&amp;title=Simplify%20Code%20by%20Encapsulating%20Locks">Submit to DZone <img src="http://www.justsoftwaresolutions.co.uk/images/dzone.png" width=16 height=16 class="sm" alt="dzone logo"></a></small></p><p><a href="http://www.justsoftwaresolutions.co.uk/threading/simplify_code_by_encapsulating_locks.html#makecomment">Comment on this post</a></p><p>Follow me on <a href="http://twitter.com/a_williams">Twitter</a></p>]]></description></item><item><title>Just::Thread now supports GCC on Windows and MacOSX</title><link>http://www.justsoftwaresolutions.co.uk/news/mingw-and-mac-support-for-just-thread.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/news/mingw-and-mac-support-for-just-thread.html</guid><pubDate>Tue, 14 Jun 2011 11:51:06 +0000</pubDate><description><![CDATA[
<p>I am pleased to announce that support for
  the <a href="http://tdm-gcc.tdragon.net/">TDM</a> port of gcc 4.5.2
  for Windows and the <a href="http://www.macports.org">MacPorts</a>
  builds of gcc 4.3, 4.4 and 4.5 have now been added
  to <a href="http://www.stdthread.co.uk"><code>just::thread</code></a>.</p>

<p>This release thus greatly improves the portability of the
  library. You can now write code
  using <a href="http://www.stdthread.co.uk"><code>just::thread</code></a>
  that will work across Windows, Linux and MacOSX. With gcc 4.5
  support across all 3 platforms, you can take advantage of the
  extensive C++0x language support from that compiler too, including
  lambda functions, rvalue references and variadic templates.</p>

<p><a href="http://www.stdthread.co.uk/order.html">Get your copy
    now</a> and add portability to your multithreaded programs.</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/mingw-and-mac-support-for-just-thread.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/just::thread" rel="tag">just::thread</a>,  <a href="http://technorati.com/tag/cplusplus" rel="tag">cplusplus</a>,  <a href="http://technorati.com/tag/multithreading" rel="tag">multithreading</a>,  <a href="http://technorati.com/tag/gcc" rel="tag">gcc</a>,  <a href="http://technorati.com/tag/windows" rel="tag">windows</a>,  <a href="http://technorati.com/tag/macosx" rel="tag">macosx</a> <br>  <div class="g-plusone" data-size="large" data-annotation="none" data-href="http://www.justsoftwaresolutions.co.uk/news/mingw-and-mac-support-for-just-thread.html"></div> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fmingw-and-mac-support-for-just-thread.html&amp;title=Just%3A%3AThread%20now%20supports%20GCC%20on%20Windows%20and%20MacOSX"> Stumble It! <img src="http://www.justsoftwaresolutions.co.uk/images/stumbleupon.png" width=16 height=16 class="sm" alt="stumbleupon logo"></a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fmingw-and-mac-support-for-just-thread.html&amp;title=Just%3A%3AThread%20now%20supports%20GCC%20on%20Windows%20and%20MacOSX">Submit to Reddit <img src="http://www.justsoftwaresolutions.co.uk/images/reddit.png" width=16 height=16 class="sm" alt="reddit logo"></a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fmingw-and-mac-support-for-just-thread.html&amp;title=Just%3A%3AThread%20now%20supports%20GCC%20on%20Windows%20and%20MacOSX">Submit to DZone <img src="http://www.justsoftwaresolutions.co.uk/images/dzone.png" width=16 height=16 class="sm" alt="dzone logo"></a></small></p><p><a href="http://www.justsoftwaresolutions.co.uk/news/mingw-and-mac-support-for-just-thread.html#makecomment">Comment on this post</a></p><p>Follow me on <a href="http://twitter.com/a_williams">Twitter</a></p>]]></description></item><item><title>just::thread C++0x Thread Library V1.6 (FDIS Edition) Released</title><link>http://www.justsoftwaresolutions.co.uk/news/just-thread-c++0x-thread-library-fdis-edition-released.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/news/just-thread-c++0x-thread-library-fdis-edition-released.html</guid><pubDate>Wed, 25 May 2011 21:48:34 +0000</pubDate><description><![CDATA[
<p>I am pleased to announce that version 1.6 (the FDIS edition)
  of <a href="http://www.stdthread.co.uk"><code>just::thread</code></a>,
  our <a href="http://www.stdthread.co.uk">C++0x Thread Library</a>
  has just been released.</p>

<p>If you're interested in C++0x, I'm sure you're aware that
the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3290.pdf">C++0x
Final Draft International Standard (FDIS)</a> was voted out at the
last C++ Standards Committee
  meeting. See <a href="https://www.ibm.com/developerworks/mydeveloperworks/blogs/5894415f-be62-4bc0-81c5-3956e82276f3/entry/the_c_0x_standard_has_been_approved_to_ship23?lang=en">Michael
    Wong's blog post</a>
  and <a href="http://herbsutter.com/2011/03/25/we-have-fdis-trip-report-march-2011-c-standards-meeting/">Herb
    Sutter's blog post</a> if you've been hiding under a rock for the
  last two months.</p>

<p>Anyway, after the vote at the meeting, the FDIS itself was
  published in April, and <a href="http://www.stdthread.co.uk"><code>just::thread</code></a> has now been
  updated to match the FDIS as close as possible. Where there have
  been changes to names (such
  as <code><a href="http://www.stdthread.co.uk/doc/headers/chrono/system_clock/to_time_point.html">std::chrono::system_clock::to_time_point</a></code>
  becoming <code><a href="http://www.stdthread.co.uk/doc/headers/chrono/system_clock/from_time_t.html">std::chrono::system_clock::from_time_t</a></code>)
  the old names have been kept, though they are marked "deprecated"
  using compiler annotations.</p>

<p>Changes include:</p>
<ul>
  <li>Support for gcc 4.6 on Ubuntu Natty (using the packages
    from <a href="https://launchpad.net/~ubuntu-toolchain-r/+archive/test?field.series_filter=natty">the
    Ubuntu Toolchain PPA</a>) and Fedora 15.</li>
  <li>Support for thread-local variables with non-trivial constructors
    and destructors using
    the <code><a href="http://www.stdthread.co.uk/doc/headers/thread/jss_thread_local.html">JSS_THREAD_LOCAL</a></code>
    macro in place of the new <code>thread_local</code> keyword (which
    is not supported in any current compilers) .</li>
  <li>The <code>std::hash&lt;std::thread::id&gt;</code> specialization
    has been added.</li>
  <li>The new <code>constexpr</code> and <code>noexcept</code>
    keywords are used where supported (gcc 4.6 in -std=c++0x mode.)</li>
  <li>The return type of lambda functions is correctly deduced
    in <code><a href="http://www.stdthread.co.uk/doc/headers/future/async.html">std::async</a></code>
    in both gcc 4.5 and 4.6 and MSVC 2010.</li>
  <li>Various optimizations, including reduction in thread creation
    code and the overhead
    of <code><a href="http://www.stdthread.co.uk/doc/headers/future/async.html">std::async</a></code>.</li>
  <li>Added <a href="http://www.stdthread.co.uk/doc/headers/chrono/system_clock/from_time_t.html">std::chrono::system_clock::from_time_t</a>
    in place
    of <code><a href="http://www.stdthread.co.uk/doc/headers/chrono/system_clock/to_time_point.html">std::chrono::system_clock::to_time_point</a></code>.</li>
</ul>

<strong><a href="http://www.stdthread.co.uk/order.html">Purchase your
copy</a> and get started with the C++0x thread library NOW.</strong></p>

<p>As usual, existing customers are entitled to a free upgrade to V1.6.0
from all earlier versions.</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/just-thread-c++0x-thread-library-fdis-edition-released.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/multithreading" rel="tag">multithreading</a>,  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a>,  <a href="http://technorati.com/tag/C++0x" rel="tag">C++0x</a> <br>  <div class="g-plusone" data-size="large" data-annotation="none" data-href="http://www.justsoftwaresolutions.co.uk/news/just-thread-c++0x-thread-library-fdis-edition-released.html"></div> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fjust-thread-c%2B%2B0x-thread-library-fdis-edition-released.html&amp;title=just%3A%3Athread%20C%2B%2B0x%20Thread%20Library%20V1.6%20%28FDIS%20Edition%29%20Released"> Stumble It! <img src="http://www.justsoftwaresolutions.co.uk/images/stumbleupon.png" width=16 height=16 class="sm" alt="stumbleupon logo"></a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fjust-thread-c%2B%2B0x-thread-library-fdis-edition-released.html&amp;title=just%3A%3Athread%20C%2B%2B0x%20Thread%20Library%20V1.6%20%28FDIS%20Edition%29%20Released">Submit to Reddit <img src="http://www.justsoftwaresolutions.co.uk/images/reddit.png" width=16 height=16 class="sm" alt="reddit logo"></a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fjust-thread-c%2B%2B0x-thread-library-fdis-edition-released.html&amp;title=just%3A%3Athread%20C%2B%2B0x%20Thread%20Library%20V1.6%20%28FDIS%20Edition%29%20Released">Submit to DZone <img src="http://www.justsoftwaresolutions.co.uk/images/dzone.png" width=16 height=16 class="sm" alt="dzone logo"></a></small></p><p><a href="http://www.justsoftwaresolutions.co.uk/news/just-thread-c++0x-thread-library-fdis-edition-released.html#makecomment">Comment on this post</a></p><p>Follow me on <a href="http://twitter.com/a_williams">Twitter</a></p>]]></description></item><item><title>Picking Patterns for Parallel Programs; slides from ACCU 2011</title><link>http://www.justsoftwaresolutions.co.uk/news/picking-patterns-for-parallel-programs-accu-2011.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/news/picking-patterns-for-parallel-programs-accu-2011.html</guid><pubDate>Mon, 18 Apr 2011 09:03:40 +0000</pubDate><description><![CDATA[
<p>On Saturday, I presented on <a
href="http://accu.org/index.php/conferences/accu_conference_2011/accu2011_sessions#Choosing%20patterns%20for%20your%20parallel%20program">Picking
Patterns for Parallel Programs</a> at ACCU 2011. We were in the
Wolvercote room again, which was packed out &mdash; <a href="http://plixi.com/p/92917003">people sat on the
floor</a> when the chairs ran out.</p>

<p>I thoroughly enjoyed it (even with the minor technical issues), and
I've had great feedback from several people who said it was really
useful to them &mdash; Dmitry even posted on twitter that it was the
<a
href="http://twitter.com/#!/dmitrykandalov/status/59224291908136960">"best
tech talk"</a>.</p>

<p>The slides are available for <a
href="http://www.justsoftwaresolutions.co.uk/files/picking_parallel_patterns.pdf">download</a>.
The 50% discount on <a
href="http://www.stdthread.co.uk">Just::thread</a> mentioned at the
end is only valid until 23rd April 2011.</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/picking-patterns-for-parallel-programs-accu-2011.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/parallelism" rel="tag">parallelism</a>,  <a href="http://technorati.com/tag/threading" rel="tag">threading</a>,  <a href="http://technorati.com/tag/accu" rel="tag">accu</a> <br>  <div class="g-plusone" data-size="large" data-annotation="none" data-href="http://www.justsoftwaresolutions.co.uk/news/picking-patterns-for-parallel-programs-accu-2011.html"></div> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fpicking-patterns-for-parallel-programs-accu-2011.html&amp;title=Picking%20Patterns%20for%20Parallel%20Programs%3B%20slides%20from%20ACCU%202011"> Stumble It! <img src="http://www.justsoftwaresolutions.co.uk/images/stumbleupon.png" width=16 height=16 class="sm" alt="stumbleupon logo"></a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fpicking-patterns-for-parallel-programs-accu-2011.html&amp;title=Picking%20Patterns%20for%20Parallel%20Programs%3B%20slides%20from%20ACCU%202011">Submit to Reddit <img src="http://www.justsoftwaresolutions.co.uk/images/reddit.png" width=16 height=16 class="sm" alt="reddit logo"></a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fpicking-patterns-for-parallel-programs-accu-2011.html&amp;title=Picking%20Patterns%20for%20Parallel%20Programs%3B%20slides%20from%20ACCU%202011">Submit to DZone <img src="http://www.justsoftwaresolutions.co.uk/images/dzone.png" width=16 height=16 class="sm" alt="dzone logo"></a></small></p><p><a href="http://www.justsoftwaresolutions.co.uk/news/picking-patterns-for-parallel-programs-accu-2011.html#makecomment">Comment on this post</a></p><p>Follow me on <a href="http://twitter.com/a_williams">Twitter</a></p>]]></description></item><item><title>Copying Exceptions in C++0x</title><link>http://www.justsoftwaresolutions.co.uk/cplusplus/copying_exceptions.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/cplusplus/copying_exceptions.html</guid><pubDate>Tue, 15 Mar 2011 23:40:12 +0000</pubDate><description><![CDATA[
<p>One of the new features of C++0x is the ability to capture
exceptions in a <code>std::exception_ptr</code> and rethrow them later
<em>without knowing what type they are</em>. This is particularly
useful, as it allows you to propagate the exceptions across threads
&mdash; you capture the exception in one thread, then pass the
<code>std::exception_ptr</code> object across to the other thread, and
then use <code>std::rethrow_exception()</code> on that other thread to
rethrow it. In fact, the exception propagation facilities
of <code>std::async</code>, <code>std::promise</code>
and <code>std::packaged_task</code> are build on this feature.</p>

<h3>To copy or not to copy</h3>

<p>The original proposal for the feature required that the exception
  was <em>copied</em> when it was captured
  with <code>std::current_exception</code>, but under pressure from
  implementors that use
  the <a href="http://www.codesourcery.com/public/cxx-abi/abi-eh.html">"Itanium
  ABI"</a> (which is actually used for other platforms too, such as
  64-bit x86 linux and MacOSX), the requirement was lessened to allow
  reference counting the exceptions instead. The problem they cited
  was that the ABI didn't store the copy constructor for exception
  objects, so when you called <code>std::current_exception()</code>
  the information required to copy the object was not present.</p>

<h3>Race conditions</h3>

<p>Unfortunately, no-one foresaw that this would open the door for
  race conditions, since the same exception object would be active on
  multiple threads at once. <strong>If any of the thread modified the
  object then there would be a data race, and undefined
  behaviour.</strong></p>

<p>It is a common idiom to catch exceptions by non-const reference in
  order to add further information to the exception, and then rethrow
  it. If this exception came from another thread (e.g. through use
  of <code>std::async</code>), then it may be active in multiple
  threads at once if it was propagated
  using <code>std::shared_future</code>, or even just
  with <code>std::exception_ptr</code> directly. Modifying the
  exception to add the additional information is thus a data race if
  done unsynchronized, but even if you add a mutex to the class you're
  still modifying an exception being used by another thread, which is
  just <em>wrong</em>.</p>

<p>Race conditions are bad enough, but these race conditions are
  implementation-dependent. The draft allows for the exceptions to be
  copied (as originally intended), and some
  compilers do that (e.g. MSVC 2010), and it also allows for them to
  be reference counted, and other compilers do that (e.g. gcc 4.5 on
  linux). This means that code that is well-defined and
  race-condition-free on MSVC 2010 might be buggy, and have data races
  when compiled with gcc 4.5, but the compiler will not (and cannot)
  warn about it. This is the nastiest of circumstances &mdash; race
  conditions silently added to working code with no warning.</p>

<h3>Dealing with the issue</h3>

<p>BSI raised an issue on the FCD about this when it came to ballot
  time. This issue
  is <a href="http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2011/n3249.html#GB74">GB-74</a>,
  and thus must be dealt with one way or the other before the C++0x
  standard is published (though sadly, "being dealt with" can mean
  that it is rejected). This is being dealt with by LWG, so is also
  listed
  as <a href="http://lwg.github.com/issues/lwg-active.html#1369">LWG
  issue 1369</a>, where there is a more complete proposed
  resolution. Unfortunately, we still need to convince the rest of the
  committee to make this change, including those implementors who use
  the Itanium ABI.</p>

<h3>Extending the ABI</h3>

<p>Fortunately, the Itanium ABI is designed to be extensible in a
  backwards-compatible manner. This means that existing code compiled
  with an existing compiler can be linked against new code compiled
  with a new compiler, and everything "just works". The old code only
  uses the facilities that existed when it was written, and the new
  code takes advantage of the new facilities. This means that the
  exception structures can be enhanced to add the necessary
  information for copying the exception (the size of the object, so
  we can allocate memory for it, and the address copy constructor, or
  a flag to say "use <code>memcpy</code>".) This isn't quite perfect,
  as exceptions thrown from old code won't have the new information,
  but provided we can detect that scenario all is well, as the
  standard draft allows us to throw <code>std::bad_exception</code>
  in that case.</p>

<p>I have written
  a <a href="http://www.justsoftwaresolutions.co.uk/files/copy_exceptions.patch">patch
  for gcc 4.5.0</a> which demonstrates this as a proof of concept.</p>

<p>This patch extends the exception structures as allowed by the ABI
  to add two fields: one for the object size, and one for the copy
  constructor. Exceptions thrown by old code will have a size of zero
  (which is illegal, so acts as a flag for old code), and thus will be
  captures as <code>std::bad_exception</code> when stored in
  a <code>std::exception_ptr</code>. Trivially copyable objects such
  as a plain <code>int</code>, or a POD <code>class</code> will have
  a <code>NULL</code> copy constructor pointer but a valid size,
  indicating that they are to be copied using <code>memcpy</code>.</p>

<p>To use the patch, get the sources for gcc 4.5.0 from your
  local <a href="http://gcc.gnu.org/mirrors.html">GCC mirror</a>,
  unpack them, and apply the patch. Then compile the patched sources
  and install your new gcc somewhere. Now, when you compile code that
  throws exceptions it will use the
  new <code>__cxa_throw_copyable</code> function in place of the
  old <code>__cxa_throw</code> function to store the requisite
  information. Unless you link against the right support code then
  your applications won't link; I found I had to use
  the <code>-static</code> command line option to force the use of the
  new exception-handling runtime rather than the standard platform
  runtime.

<pre>
    /opt/newgcc/bin/g++ -std=c++0x -static foo.cpp -o foo
</pre>

<p>Note that if the copy constructor of the exception is not thread
  safe then there might still be an issue when
  using <code>std::exception_ptr</code>, as my patch doesn't include a
  mutex. However, this would be an easy extension to make now the
  proof of concept has been done. I also expect that there are cases
  that don't behave quite right, as I am far from being an expert on
  the gcc internals.</p>

<p>Hopefully, this proof of concept will help convince the rest of the
  C++ committee to accept GB-74 at the meeting in Madrid next
  week.</p>

<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/cplusplus/">cplusplus</a> /] <a href="http://www.justsoftwaresolutions.co.uk/cplusplus/copying_exceptions.html">permanent link</a></i><br> <small> Tags:  <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/WG21" rel="tag">WG21</a>,  <a href="http://technorati.com/tag/Exceptions" rel="tag">Exceptions</a>,  <a href="http://technorati.com/tag/Copying" rel="tag">Copying</a>,  <a href="http://technorati.com/tag/exception_ptr" rel="tag">exception_ptr</a>,  <a href="http://technorati.com/tag/rethrow_exception" rel="tag">rethrow_exception</a> <br>  <div class="g-plusone" data-size="large" data-annotation="none" data-href="http://www.justsoftwaresolutions.co.uk/cplusplus/copying_exceptions.html"></div> | <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fcplusplus%2Fcopying_exceptions.html&amp;title=Copying%20Exceptions%20in%20C%2B%2B0x"> Stumble It! <img src="http://www.justsoftwaresolutions.co.uk/images/stumbleupon.png" width=16 height=16 class="sm" alt="stumbleupon logo"></a> | <a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fcplusplus%2Fcopying_exceptions.html&amp;title=Copying%20Exceptions%20in%20C%2B%2B0x">Submit to Reddit <img src="http://www.justsoftwaresolutions.co.uk/images/reddit.png" width=16 height=16 class="sm" alt="reddit logo"></a> | <a href="http://www.dzone.com/links/add.html?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fcplusplus%2Fcopying_exceptions.html&amp;title=Copying%20Exceptions%20in%20C%2B%2B0x">Submit to DZone <img src="http://www.justsoftwaresolutions.co.uk/images/dzone.png" width=16 height=16 class="sm" alt="dzone logo"></a></small></p><p><a href="http://www.justsoftwaresolutions.co.uk/cplusplus/copying_exceptions.html#makecomment">Comment on this post</a></p><p>Follow me on <a href="http://twitter.com/a_williams">Twitter</a></p>]]></description></item></channel></rss>
