<?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-8 Just Software Solutions Ltd.</copyright> 

	<managingEditor>Anthony Williams</managingEditor> 

	<webMaster>info@justsoftwaresolutions.co.uk</webMaster><item><title>June 2009 C++ Standards Committee Mailing - New Working Draft and Concurrency Papers</title><link>http://www.justsoftwaresolutions.co.uk/cplusplus/cplusplus-standards-committee-mailing-june-2009.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/cplusplus/cplusplus-standards-committee-mailing-june-2009.html</guid><pubDate>Wed, 24 Jun 2009 22:21:23 +0100</pubDate><description><![CDATA[
<p>The <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/#mailing2009-06">June 2009 mailing</a> for the C++ Standards Committee was
published today. This is the pre-meeting mailing for the upcoming
committee meeting. Not only does it include the current <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2914.pdf">C++0x
working draft</a>, but there are 39 other papers, of which 6 are
concurrency related.</p>

<h3>Concurrency-related papers</h3>

<dl>
<dt><a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2880.html">N2880:
C++ object lifetime interactions with the threads API</a></dt>
<dd><p>This is a repeat of the same paper from the <a
href="http://www.justsoftwaresolutions.co.uk/cplusplus/cplusplus-standards-committee-mailing-may-2009.html">May
2009 mailing</a>. It is referenced by several of the other concurrency
papers.</p></dd>

<dt><a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2888.html">N2888:
Moving Futures - Proposed Wording for UK comments 335, 336, 337 and
338</a></dt>

<dd><p>This is the first of my papers in this mailing. The current
working draft restricts <a
href="http://www.stdthread.co.uk/doc/headers/future/unique_future.html"><code>std::unique_future</code></a>
to be <code>MoveConstructible</code>, but not
<code>MoveAssignable</code>. It also restricts <a
href="http://www.stdthread.co.uk/doc/headers/future/shared_future.html"><code>std::shared_future</code></a>
in a similar way, by making it <code>CopyConstructible</code>, but not
<code>CopyAssignable</code>. This severely limits the potential use of
such futures, so the UK panel filed comments on CD1 such as <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2898.html#UK335">UK
comment 335</a> which requested relaxation of these unnecessary
restrictions. This paper to provide a detailed rationale for these
changes, along with proposed wording.</p></dd>

<dt><a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2889.html">N2889:
An Asynchronous Call for C++</a></dt>

<dd><p>This is the first of two papers in the mailing that proposes a
<code>std::async()</code> function for starting a task possibly
asynchronously and returning a future for the result from that
task. This addresses a need identified by <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2898.html#UK329">UK
comment 329</a> on CD1 for a simple way of starting a task with a
return value asynchronously.</p></dd>

<dt><a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2901.pdf">N2901:
A simple async()</a></dt>

<dd><p>This is the second of the papers in the mailing that proposes a
<code>std::async()</code> function for starting a task possibly
asynchronously and returning a future for the result from that
task.</p>

<p>The primary difference between the papers is the type of the
returned future. N2889 proposes a new type of future
(<code>joining_future</code>), whereas N2901 proposes using
<a
href="http://www.stdthread.co.uk/doc/headers/future/unique_future.html"><code>std::unique_future</code></a>. There are also a few semantic
differences surrounding whether tasks that run asynchronously aways do
so on a new thread, or whether they may run on a thread that is reused
for multiple tasks. Both papers provide a means for the caller to
specify synchronous execution of tasks, or to allow the implementation
to decide between synchronous execution and asynchronous execution on
a case-by-case basis. N2901 also explicitly relies on the use of
lambda functions or <code>std::bind</code> to bind parameters to a
call, whereas N2889 supports specifying function arguments as
additional parameters, as per the <a
href="http://www.stdthread.co.uk/doc/headers/thread/thread/constructor.html"><code>std::thread</code>
constructor</a> (see my <a
href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-2-function-objects-and-arguments.html">introduction
to starting threads with arguments in C++0x</a>).</p>

<p>Personally, I prefer the use of <a
href="http://www.stdthread.co.uk/doc/headers/future/unique_future.html"><code>std::unique_future</code></a>
proposed in N2901, but I rather like the argument-passing semantics of
N2889. I also think that the <code>thread_local</code> issues can be
addressed by my proposal for that (N2907, see below). A final concern
that I have is that calling the task inside <code>future::get()</code>
can yield surprising behaviour, as futures can be passed across
threads, so this may end up being called on another thread
altogether. For synchronous execution, I would prefer invoking the
task inside the <code>std::async</code> call itself, but delaying it
to the <code>get()</code> does allow for work-stealing thread
pools.</p></dd>

<dt><a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2907.html">N2907:
Managing the lifetime of thread_local variables with contexts</a></dt>

<dd><p>This is the second of my papers in this mailing. It proposes a
potential solution to the
lifetime-of-<code>thread_local</code>-variables issues from N2880
discussed in <a
href="http://www.justsoftwaresolutions.co.uk/cplusplus/cplusplus-standards-committee-mailing-may-2009.html">last
month's blog post</a>.</p>

<p>The idea is that you manage the lifetime of
<code>thread_local</code> variables by constructing an instance of a
new class <code>std::thread_local_context</code>. When the
<code>std::thread_local_context</code> instance is destroyed, all
<code>thread_local</code> variables created in that context are also
destroyed. You can then construct a subsequent instance of
<code>std::thread_local_context</code>, and create new
<code>thread_local</code> instances in that new context. This means
that you can reuse a thread for multiple unrelated tasks, without
"spilling" <code>thread_local</code> variables from an earlier task
into later tasks. It can also be used with a <code>std::async()</code>
function to ensure that the <code>thread_local</code> variables are
destroyed before the associated future is made ready.</p></dd>

<dt><a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2917.pdf">N2917:
N2880 Distilled, and a New Issue With Function Statics</a></dt>

<dd><p>This is Herb Sutter's take on the issues from N2880. He starts
with a general discussion of the issue with detached threads and
static destruction of globals, and then continues with a discussion of
the issues surrounding the destruction of function-scoped
<code>thread_local</code> variables. In particular, Herb focuses on
something he calls <em>Function <code>thread_local</code> statics
poisoning <code>thread_local</code> destructors</em> &mdash; if the
destructor of a <code>thread_local</code> object <code>x</code> calls a function that
itself uses a function-scope <code>thread_local</code> <code>y</code>,
then the destructor of <code>y</code> might already have been called,
resulting in undefined behaviour.</p>

<p>I found Herb's coverage of the issues surrounding detached threads
dismissive of the idea that people could correctly write manual
synchronization (e.g. using a <a
href="http://www.stdthread.co.uk/doc/headers/condition_variable/condition_variable.html"><code>std::condition_variable</code></a>
or a <a
href="http://www.stdthread.co.uk/doc/headers/future/unique_future.html"><code>std::unique_future</code></a>),
even though this is common practice amongst those using POSIX threads
(for example, in David Butenhof's <em>Programming with POSIX
Threads</em>, he says "pthread_join is a convenience, not a rule", and
describes examples using detached threads and condition variables to
signal when the thread is done). I can see many possibilities for such
usage, so as a consequence, I am personally in favour of his
"solution" 1D: leave things as they are with regard to detached
threads &mdash; it is already undefined behaviour to access something
after its destruction.</p>

<p>However, the issue Herb raises with regard to order of destruction
for <code>thread_local</code> variables is important, and not
something that my <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2907.html"><code>std::thread_local_context</code>
proposal</a> addresses. As Herb points out, the problem does exist
with regard to function-local <code>static</code> variables already
&mdash; <code>thread_local</code> just amplifies the problem. I am
inclined to go with what POSIX threads does, and what
<code>boost::thread_specific_ptr</code> does: make them "phoenix"
variables that are re-initialized when accessed after destruction,
and are thus added back onto the destructor list. This is Herb's
solution 2B.</p></dd>

</dl>

<h3>Other papers</h3>

<p>Now that CD1 is out, and the committee is trying to get things
pinned down for CD2, Concepts are getting a lot of discussion. There
are therefore several papers on Concepts in the mailing. There are
also papers on automatically defining move constructors, revised
wording for lambdas, a proposal for unifying the function syntax, and
several others. Check out the <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/#mailing2009-06">full
list of papers</a> for details.</p>

<h3>Your comments</h3>

<p>Do you have any comments on the papers (especially the concurrency
ones, but if you have any comments on the others I'd like to know
too)? Which <code>std::async</code> proposal do you prefer, or do you
like aspects of both or neither? Do you think that
<code>thread_local_context</code> objects combined with resurrecting
<code>thread_local</code> objects on post-destruction access solves
the <code>thread_local</code> issues?</p>

<p>Let me know by <a
href="http://www.justsoftwaresolutions.co.uk/cplusplus/cplusplus-standards-committee-mailing-june-2009.html#makecomment">posting
a comment</a>.</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/cplusplus-standards-committee-mailing-june-2009.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/C++0x" rel="tag">C++0x</a>,  <a href="http://technorati.com/tag/C++" rel="tag">C++</a>,  <a href="http://technorati.com/tag/standards" rel="tag">standards</a>,  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a> <br>  <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fcplusplus%2Fcplusplus-standards-committee-mailing-june-2009.html&amp;title=June%202009%20C%2B%2B%20Standards%20Committee%20Mailing%20-%20New%20Working%20Draft%20and%20Concurrency%20Papers"> 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%2Fcplusplus-standards-committee-mailing-june-2009.html&amp;title=June%202009%20C%2B%2B%20Standards%20Committee%20Mailing%20-%20New%20Working%20Draft%20and%20Concurrency%20Papers">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%2Fcplusplus-standards-committee-mailing-june-2009.html&amp;title=June%202009%20C%2B%2B%20Standards%20Committee%20Mailing%20-%20New%20Working%20Draft%20and%20Concurrency%20Papers">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/cplusplus-standards-committee-mailing-june-2009.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>Importing an Existing Windows XP Installation into VirtualBox</title><link>http://www.justsoftwaresolutions.co.uk/general/importing-windows-into-virtualbox.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/general/importing-windows-into-virtualbox.html</guid><pubDate>Wed, 03 Jun 2009 14:41:23 +0100</pubDate><description><![CDATA[
<p>On Monday morning one of the laptops I use for developing software
died. Not a complete "nothing happens when I turn it on" kind of death
&mdash; it still runs the POST checks OK &mdash; but it won't rebooted
of its own accord whilst compiling some code and now no longer boots
into Windows (no boot device, apparently). Now, I really didn't fancy
having to install everything from scratch, and I've become quite a big
fan of <a href="http://www.virtualbox.org">VirtualBox</a> recently, so
I thought I'd import it into VirtualBox. How hard could it be? The
answer, I discovered, was "quite hard".</p>

<p>Since it seems that several other people have tried to import an
existing Windows XP installation into VirtualBox and had problems doing
so, I thought I'd document what I did for the benefits of anyone who
is foolish enough to try this in the future.</p>

<h3>Step 1: Clone the Disk into VirtualBox</h3>

<p>The first thing to do is clone the disk into VirtualBox. I have a
handy laptop disk caddy lying around in my office which enables you to
convert a laptop hard disk into an external USB drive, so I took the
disk out of the laptop and put it in that. I connected the drive to my
linux box, and mounted the partition. A quick look round seemed to
indicate that the partition was in working order and the data
intact. So far so good. I unmounted the partition again, in
preparation for cloning the disk.</p>

<p>I started VirtualBox and created a new virtual
machine with a virtual disk the same size as the physical disk. I then
booted the VM with the <a href="http://www.sysresccd.org">System
Rescue CD</a> that I use for partitioning and disk backups. You might
prefer to use another disk cloning tool.</p>

<p>Once the VM was up and running, I connected the USB drive to the VM
using VirtualBox's USB support and cloned the physical disk onto the
virtual one. This took a <strong>long</strong> time, considering it
was only a 30Gb disk. Someone will probably tell me that there are
quicker ways of doing this, but it worked, and I hope I don't have to
do it again.</p>

<h3>Step 2: Try (and fail) to boot Windows</h3>

<p>Once the clone was complete, I disconnected the USB drive and
unmapped the System Rescue CD and rebooted the VM. Windows started to
boot, but would hang on the splash screen. If you're trying this and
Windows now boots in your VM, be very glad.</p>

<p>Booting into safe mode showed that the hang occurred after loading
"mup.sys". It seems lots of people have had this problem, and mup.sys
is not the problem &mdash; the problem is that the hardware drivers
configured for the existing Windows installation don't match the
VirtualBox emulated hardware in some drastic fashion. This is not
surprising if you think about it. Anyway, like I said, lots of people
have had this problem, and there are lots of suggested ways of fixing
it, like booting with the Windows Recovery Console and adjusting which
drivers are loaded, using the "repair" version of the registry and so
forth. I tried most of them, and none worked. However, there was one
suggestion that seemed worth following through, and it was a variant
of this that I finally got working.</p>

<h3>Step 3: Install Windows into a new VM</h3>

<p>The suggestion that I finally got working was to install Windows on
a new VM and swipe the SYSTEM registry hive from there. This registry
hive contains all the information about your hardware that Windows
needs to boot, so if you can get Windows booting in a VM then you can
use the corresponding SYSTEM registry hive to boot the recovered
installation. At least that's the theory; in practice it needs a bit
of hackery to make it work.</p>

<p>Anyway, I installed Windows into the new VM, closed it down
rebooted it with the System Rescue CD to retrieve the SYSTEM registry
hive: C:\Windows\System32\config\SYSTEM. You cannot access this file
when the system is running. I then booted my original VM with the
System Rescue CD and copied the registry hive over, <strong>making
sure I had a backup of the original</strong>. If you're doing this
yourself <strong>don't change the hive on your original VM
yet</strong>.</p>

<p>The system now booted into Windows. Well, almost &mdash; it booted
up, but then displayed an LSASS message about being unable to update
the password and rebooted. This cycle repeats ad infinitum, even in
Safe Mode. So far not so good.</p>

<h3>Step 4: Patching the SYSKEY</h3>

<p>In practice, Windows installations have what's called a SYSKEY in
order to prevent unauthorized people logging on to the system. This is
a checksum of some variety which is spread across the SAM registry
hive (which contains the user details), the SYSTEM hive and the
SECURITY hive. If the SYSKEY is wrong, the system will boot up, but
then display the message I was getting about LSASS being unable to
update the password and reboot. In theory, you should be able to
update all three registry hives together, but then all your user
accounts get replaced, and I didn't fancy trying to get everything set
up right again. This is where the hackery comes in, and where I am
thankful to two people: firstly Clark from <a
href="http://www.beginningtoseethelight.org/">http://www.beginningtoseethelight.org/</a>
who wrote an informative article on the <a
href="http://www.beginningtoseethelight.org/ntsecurity/index.php">Windows
Security Accounts Manager</a> which explains how the SYSKEY is stored
in the registry hives, and secondly Petter Nordahl-Hagen who provides
a boot disk for <a
href="http://home.eunet.no/~pnordahl/ntpasswd/">offline Windows
password and registry editing</a>.</p>

<p>According to the article on the Windows Security Manager, the
portion of the SYSKEY store in the SYSTEM hive is stored as class key
values on a few registry keys. Class key values are hidden from normal
registry accesses, but Petter Nordahl-Hagen's registry editor can show
them to you. So, I restored the original SYSTEM hive (I was glad I
made a backup) and booted the VM from Petter's boot disk and looked at
the class key values on the ControlSet001\Control\Lsa\Data,
ControlSet001\Control\Lsa\GBG, ControlSet001\Control\Lsa\JD and
ControlSet001\Control\Lsa\Skew1 keys from the SYSTEM hive. I noted
these down for later. The values are all 16 bytes long: the ASCII
values for 8 hex digits with null bytes between.</p>

<p>This is where the hackery comes in &mdash; I loaded the new SYSTEM
hive (from the working Windows VM) into a hex editor and searched for
the GBG key. The text should appear in a few places &mdash; one for
the subkey of ControlSet001, one for the subkey of ControlSet002, and
so forth. A few bytes after one of the occurrences you should see a
sequence of 16 bytes that looks similar to the codes you wrote down:
ASCII values for hex digits separated by spaces. Make a note of the
original sequence and replace it with the GBG class key value from the
working VM. Do the same for the Data, JD and Skew1 values. Near the
Data values you should also see the same hex digit sequence without
the separating null bytes. Replace that too. Now look at the values in
the file near to where the registry key names occur to see if there
are any other occurrences of the original hex digit sequences and
replace these with the new values as well.</p>

<p>Save the patched SYSTEM registry hive and copy it into the VM being
recovered.</p>

<p>Now for the moment of truth: boot the VM. If you've patched all the
values correctly then it will boot into Windows. If not, then you'll
get the LSASS message again. In this case, try booting into the "Last
Known Good Configuration". This might work if you missed one of the
occurrences of the original values. If it still doesn't work, load the
hive back into your hex editor and have another go.</p>

<h3>Step 5: Activate Windows and Install VirtualBox Guest Additions</h3>

<p>Once Windows has booted successfully, it will update the SYSKEY
entries across the remaining ControlSetXXX entries, so you don't need
to worry if you missed some values. You'll need to re-activate Windows
XP due to the huge change in hardware, but this should be relatively
painless &mdash; if you enable a network adapter in the VM
configuration then Windows can access the internet through your host's
connection seamlessly. Once that's done you can proceed with install
the VirtualBox guest additions to make it easier to work with the VM
&mdash; mouse pointer integration, sensible screen resolutions, shared
folders and so forth.</p>

<p>Was it quicker than installing everything from scratch? Possibly: I
had a lot of software installed. It was certainly a lot more
touch-and-go, and it was a bit scary patching the registry hive in a
hex editor. It was quite fun though, and it felt good to get it
working.</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/importing-windows-into-virtualbox.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/virtualbox" rel="tag">virtualbox</a> <br>  <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fgeneral%2Fimporting-windows-into-virtualbox.html&amp;title=Importing%20an%20Existing%20Windows%20XP%20Installation%20into%20VirtualBox"> 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%2Fimporting-windows-into-virtualbox.html&amp;title=Importing%20an%20Existing%20Windows%20XP%20Installation%20into%20VirtualBox">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%2Fimporting-windows-into-virtualbox.html&amp;title=Importing%20an%20Existing%20Windows%20XP%20Installation%20into%20VirtualBox">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/importing-windows-into-virtualbox.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>May 2009 C++ Standards Committee Mailing - Object Lifetimes and Threads</title><link>http://www.justsoftwaresolutions.co.uk/cplusplus/cplusplus-standards-committee-mailing-may-2009.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/cplusplus/cplusplus-standards-committee-mailing-may-2009.html</guid><pubDate>Mon, 18 May 2009 22:36:41 +0100</pubDate><description><![CDATA[
<p>The <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/#mailing2009-05">May 2009 mailing</a> for the C++ Standards Committee was
published a couple of weeks ago. This is a minimal mailing between
meetings, and only has a small number of papers.</p>

<p>The primary reason I'm mentioning it is because one of the papers
is concurrency related: <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2880.html">N2880:
C++ object lifetime interactions with the threads API</a> by
Hans-J. Boehm and Lawrence Crowl. Hans and Lawrence are concerned
about the implications of <code>thread_local</code> objects with destructors, and
how you can safely clean up threads if you don't call <a
href="http://www.stdthread.co.uk/doc/headers/thread/thread/join.html"><code>join()</code></a>. The
issue arose during discussion of the proposed <code>async()</code>
function, but is generally applicable.</p>

<h3><code>thread_local</code> variables and detached threads</h3>

<p>Suppose you run a function on a thread for which you want the
return value. You might be tempted to use <a
href="http://www.stdthread.co.uk/doc/headers/future/packaged_task.html"><code>std::packaged_task&lt;&gt;</code></a>
and <a
href="http://www.stdthread.co.uk/doc/headers/future/unique_future.html"><code>std::unique_future&lt;&gt;</code></a>
for this; after all it's almost exactly what they're designed for:

<pre class="listing">
#include &lt;thread&gt;
#include &lt;future&gt;
#include &lt;iostream&gt;

int find_the_answer_to_LtUaE();

std::unique_future&lt;int&gt; start_deep_thought()
{
    std::packaged_task&lt;int()&gt; task(find_the_answer_to_LtUaE);
    std::unique_future&lt;int&gt; future=task.get_future();
    std::thread t(std::move(task));
    t.detach();
    return future;
}

int main()
{
    std::unique_future&lt;int&gt; the_answer=start_deep_thought();
    do_stuff();
    std::cout&lt;&lt;"The answer="&lt;&lt;the_answer.get()&lt;&lt;std::endl;
}
</pre>

<p>The call to <a
href="http://www.stdthread.co.uk/doc/headers/future/unique_future/get.html"><code>get()</code></a>
will wait for the <em>task</em> to finish, but not the
<em>thread</em>. If there are no <code>thread_local</code> variable
this is not a problem &mdash; the thread is detached so the library
will clean up the resources assigned to it automatically. If there
<em>are</em> <code>thread_local</code> variables (used in
<code>find_the_answer_to_LtUaE()</code> for example), then this
<em>does</em> cause a problem, because their destructors are not
guaranteed to complete when <a
href="http://www.stdthread.co.uk/doc/headers/future/unique_future/get.html"><code>get()</code></a>
returns. Consequently, the program may exit before the destructors of
the <code>thread_local</code> variables have completed, and we have a
race condition.</p>

<p>This race condition is particularly problematic if the thread
accesses any objects of static storage duration, such as global
variables. The program is exiting, so these are being destroyed; if
the <code>thread_local</code> destructors in the still-running thread
access global variables that have already been destroyed then your
program has undefined behaviour.</p>

<p>This isn't the only problem that Hans and Lawrence discuss &mdash;
they also discuss problems with <code>thread_local</code> and threads
that are reused for multiple tasks &mdash; but I think it's the most
important issue.</p>

<h3>Solutions?</h3>

<p>None of the solutions proposed in the paper are ideal. I
particularly dislike the proposed removal of the <a
href="http://www.stdthread.co.uk/doc/headers/thread/thread/detach.html"><code>detach()</code></a>
member function from <a
href="http://www.stdthread.co.uk/doc/headers/thread/thread.html"><code>std::thread</code></a>. If
you can't detach a thread directly then it makes functions like
<code>start_deep_thought()</code> much harder to write, and people
will find ways to simulate detached threads another way. Of the
options presented, my preferred choice is to allow registration of a
thread termination handler which is run after all
<code>thread_local</code> objects have been destroyed. This handler
can then be used to set the value on a future or notify a condition
variable. However, it would make <code>start_deep_thought()</code>
more complicated, as <a
href="http://www.stdthread.co.uk/doc/headers/future/packaged_task.html"><code>std::packaged_task&lt;&gt;</code></a>
wouldn't automatically make use of this mechanism unless it was
extended to do so &mdash; if it did this every time then it would make
it unusable in other contexts.</p>

<p>If anyone has any suggestions on how to handle the issue, please
leave them in the comments below and I'll pass them on to the rest of
the committee.</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/cplusplus-standards-committee-mailing-may-2009.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/C++0x" rel="tag">C++0x</a>,  <a href="http://technorati.com/tag/C++" rel="tag">C++</a>,  <a href="http://technorati.com/tag/standards" rel="tag">standards</a>,  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a> <br>  <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fcplusplus%2Fcplusplus-standards-committee-mailing-may-2009.html&amp;title=May%202009%20C%2B%2B%20Standards%20Committee%20Mailing%20-%20Object%20Lifetimes%20and%20Threads"> 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%2Fcplusplus-standards-committee-mailing-may-2009.html&amp;title=May%202009%20C%2B%2B%20Standards%20Committee%20Mailing%20-%20Object%20Lifetimes%20and%20Threads">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%2Fcplusplus-standards-committee-mailing-may-2009.html&amp;title=May%202009%20C%2B%2B%20Standards%20Committee%20Mailing%20-%20Object%20Lifetimes%20and%20Threads">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/cplusplus-standards-committee-mailing-may-2009.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>&quot;Introduction to Variadic Templates in C++0x&quot; Article Online</title><link>http://www.justsoftwaresolutions.co.uk/news/introduction-to-variadic-templates-in-c++0x.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/news/introduction-to-variadic-templates-in-c++0x.html</guid><pubDate>Thu, 07 May 2009 11:32:38 +0100</pubDate><description><![CDATA[
<p>My latest article, <a
href="http://www.devx.com/cplus/Article/41533">Introduction to
Variadic Templates in C++0x</a> has been published at <a
href="http://www.devx.com">devx.com</a>.</p>

<p>This article introduces the syntax for declaring and using variadic
templates, along with some simple examples of variadic function
templates and variadic class templates.</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/introduction-to-variadic-templates-in-c++0x.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/article" rel="tag">article</a>,  <a href="http://technorati.com/tag/variadic+templates" rel="tag">variadic templates</a>,  <a href="http://technorati.com/tag/C++0x" rel="tag">C++0x</a> <br>  <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fintroduction-to-variadic-templates-in-c%2B%2B0x.html&amp;title=%22Introduction%20to%20Variadic%20Templates%20in%20C%2B%2B0x%22%20Article%20Online"> 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%2Fintroduction-to-variadic-templates-in-c%2B%2B0x.html&amp;title=%22Introduction%20to%20Variadic%20Templates%20in%20C%2B%2B0x%22%20Article%20Online">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%2Fintroduction-to-variadic-templates-in-c%2B%2B0x.html&amp;title=%22Introduction%20to%20Variadic%20Templates%20in%20C%2B%2B0x%22%20Article%20Online">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/introduction-to-variadic-templates-in-c++0x.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>Designing Multithreaded Applications with C++0x: ACCU 2009 Slides</title><link>http://www.justsoftwaresolutions.co.uk/news/designing-multithreaded-applications-with-c++0x-accu-2009-slides.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/news/designing-multithreaded-applications-with-c++0x-accu-2009-slides.html</guid><pubDate>Tue, 28 Apr 2009 16:01:14 +0100</pubDate><description><![CDATA[
<p>The <a
href="http://accu.org/index.php/conferences/accu_conference_2009/">ACCU
2009</a> conference has now finished, and life is getting back to
normal. My presentation on <a
href="http://accu.org/index.php/conferences/accu_conference_2009/accu2009_sessions#Designing%20multithreaded%20applications%20in%20C++0x">"Designing
Multithreaded Programs with C++0x"</a> was well attended and I had a
few people come up to me afterwards to say they enjoyed it, which is
always nice.</p>

<p>Anyway, the purpose of this post is to say that the <a
href="http://www.justsoftwaresolutions.co.uk/files/designing_mt_programs.pdf">slides</a>
are now up. I've also posted the <a
href="http://www.justsoftwaresolutions.co.uk/files/designing_mt_programs_examples.zip">sample
code</a> for the Concurrent Queue and Numerical Integration
demonstrations that I did using our <a
href="http://www.stdthread.co.uk"><code>just::thread</code></a>
implementation of the C++0x thread library.</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/designing-multithreaded-applications-with-c++0x-accu-2009-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/threading" rel="tag">threading</a>,  <a href="http://technorati.com/tag/accu" rel="tag">accu</a>,  <a href="http://technorati.com/tag/C++0x" rel="tag">C++0x</a> <br>  <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fdesigning-multithreaded-applications-with-c%2B%2B0x-accu-2009-slides.html&amp;title=Designing%20Multithreaded%20Applications%20with%20C%2B%2B0x%3A%20ACCU%202009%20Slides"> 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%2Fdesigning-multithreaded-applications-with-c%2B%2B0x-accu-2009-slides.html&amp;title=Designing%20Multithreaded%20Applications%20with%20C%2B%2B0x%3A%20ACCU%202009%20Slides">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%2Fdesigning-multithreaded-applications-with-c%2B%2B0x-accu-2009-slides.html&amp;title=Designing%20Multithreaded%20Applications%20with%20C%2B%2B0x%3A%20ACCU%202009%20Slides">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/designing-multithreaded-applications-with-c++0x-accu-2009-slides.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 discount for ACCU 2009</title><link>http://www.justsoftwaresolutions.co.uk/news/just-thread-accu-2009-discount.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/news/just-thread-accu-2009-discount.html</guid><pubDate>Mon, 20 Apr 2009 23:32:54 +0100</pubDate><description><![CDATA[
<p>As I mentioned <a
href="http://www.justsoftwaresolutions.co.uk/news/designing-multithreaded-applications-with-c++0x-accu-2009.html">back
in January</a>, I will be speaking on <a
href="http://accu.org/index.php/conferences/accu_conference_2009/accu2009_sessions#Designing%20multithreaded%20applications%20in%20C++0x">"Designing
Multithreaded Applications with C++0x"</a> at ACCU 2009 on
Thursday.</p>

<p>To coincide with my presentation, our <a
href="http://www.stdthread.co.uk">C++0x thread library</a>, <a
href="http://www.stdthread.co.uk"><code>just::thread</code></a> is
available at a <a href="http://www.stdthread.co.uk/accu2009/">25%
discount</a> until the 4th May 2009. <code>just::thread</code>
provides implementations of the C++0x thread library facilities such
as <a
href="http://www.stdthread.co.uk/doc/headers/thread/thread.html">std::thread</a>,
<a
href="http://www.stdthread.co.uk/doc/headers/mutex/mutex.html">std::mutex</a>,
<a
href="http://www.stdthread.co.uk/doc/headers/future/unique_future.html">std::unique_future&lt;&gt;</a>
and <a
href="http://www.stdthread.co.uk/doc/headers/cstdatomic/atomic.html">std::atomic&lt;&gt;</a>. The
current release works with Microsoft Visual Studio 2008, and gcc/linux
support will be available soon &mdash; it is currently undergoing
alpha testing.</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-accu-2009-discount.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/threading" rel="tag">threading</a>,  <a href="http://technorati.com/tag/accu" rel="tag">accu</a>,  <a href="http://technorati.com/tag/C++0x" rel="tag">C++0x</a>,  <a href="http://technorati.com/tag/just::thread" rel="tag">just::thread</a> <br>  <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fnews%2Fjust-thread-accu-2009-discount.html&amp;title=just%3A%3Athread%20discount%20for%20ACCU%202009"> 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-accu-2009-discount.html&amp;title=just%3A%3Athread%20discount%20for%20ACCU%202009">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-accu-2009-discount.html&amp;title=just%3A%3Athread%20discount%20for%20ACCU%202009">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-accu-2009-discount.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>Multithreading in C++0x part 4: Protecting Shared Data</title><link>http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-4-protecting-shared-data.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-4-protecting-shared-data.html</guid><pubDate>Sat, 04 Apr 2009 00:35:45 +0100</pubDate><description><![CDATA[
<p><em>This is the fourth of a series of blog posts introducing the
new C++0x thread library. The first three parts covered <a
href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-C++0x-part-1-starting-threads.html">starting
threads in C++0x</a> with simple functions, <a
href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-C++0x-part-2-function-objects-and-arguments.html">starting
threads with function objects and additional arguments</a>, and <a
href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-C++0x-part-3.html">starting
threads with member functions and reference arguments</a>.</em></p>

<p>If you've read the previous parts of the series then you should be
comfortable with starting threads to perform tasks "in the
background", and waiting for them to finish. You can accomplish a lot
of useful work like this, passing in the data to be accessed as
parameters to the thread function, and then retrieving the result when
the thread has completed. However, this won't do if you need to
communicate between the threads whilst they are running &mdash;
accessing shared memory concurrently from multiple threads causes
undefined behaviour if either thread modifies the data. What you need
here is some way of ensuring that the accesses are <em>mutually
exlusive</em>, so only one thread can access the shared data at a
time.</p>

<h3>Mutual Exclusion with <code><a
href="http://www.stdthread.co.uk/doc/headers/mutex/mutex.html">std::mutex</a></code></h3>

<p>Mutexes are conceptually simple. A mutex is either "locked" or
"unlocked", and threads try and lock the mutex when they wish to
access some protected data. If the mutex is already locked then any
other threads that try and lock the mutex will have to wait. Once the
thread is done with the protected data it unlocks the mutex, and
another thread can lock the mutex. If you make sure that threads
always lock a particular mutex before accessing a particular piece of
shared data then other threads are excluded from accessing the data
until as long as another thread has locked the mutex. This prevents
concurrent access from multiple threads, and avoids the undefined
behaviour of data races. The simplest mutex provided by C++0x is
<code><a
href="http://www.stdthread.co.uk/doc/headers/mutex/mutex.html">std::mutex</a></code>.</p>

<p>Now, whilst <code><a
href="http://www.stdthread.co.uk/doc/headers/mutex/mutex.html">std::mutex</a></code>
has member functions for explicitly locking and unlocking, by far the
most common use case in C++ is where the mutex needs to be locked for
a specific region of code. This is where the <code><a
href="http://www.stdthread.co.uk/doc/headers/mutex/lock_guard.html">std::lock_guard&lt;&gt;</a></code>
template comes in handy by providing for exactly this scenario. The
constructor locks the mutex, and the destructor unlocks the mutex, so
to lock a mutex for the duration of a block of code, just construct a
<code><a
href="http://www.stdthread.co.uk/doc/headers/mutex/lock_guard.html">std::lock_guard&lt;&gt;</a></code>
object as a local variable at the start of the block. For example, to
protect a shared counter you can use <code><a
href="http://www.stdthread.co.uk/doc/headers/mutex/lock_guard.html">std::lock_guard&lt;&gt;</a></code>
to ensure that the mutex is locked for either an increment or a query
operation, as in the following example:</p>

<pre class="listing">
std::mutex m;
unsigned counter=0;

unsigned increment()
{
    std::lock_guard&lt;std::mutex&gt; lk(m);
    return ++counter;
}
unsigned query()
{
    std::lock_guard&lt;std::mutex&gt; lk(m);
    return counter;
}
</pre>

<p>This ensures that access to <code>counter</code> is
<em>serialized</em> &mdash; if more than one thread calls
<code>query()</code> concurrently then all but one will block until
the first has exited the function, and the remaining threads will then
have to take turns. Likewise, if more than one thread calls
<code>increment()</code> concurrently then all but one will
block. Since both functions lock the <em>same</em> mutex, if one
thread calls <code>query()</code> and another calls
<code>increment()</code> at the same time then one or other will have
to block. This <em>mutual exclusion</em> is the whole point of a
mutex.</p>

<h3>Exception Safety and Mutexes</h3>

<p>Using <code><a
href="http://www.stdthread.co.uk/doc/headers/mutex/lock_guard.html">std::lock_guard&lt;&gt;</a></code>
to lock the mutex has additional benefits over manually locking and
unlocking when it comes to exception safety. With manual locking, you
have to ensure that the mutex is unlocked correctly on every exit path
from the region where you need the mutex locked, <em>including when
the region exits due to an exception</em>. Suppose for a moment that
instead of protecting access to a simple integer counter we were
protecting access to a <code>std::string</code>, and appending parts
on the end. Appending to a string might have to allocate memory, and
thus might throw an exception if the memory cannot be
allocated. With <code><a
href="http://www.stdthread.co.uk/doc/headers/mutex/lock_guard.html">std::lock_guard&lt;&gt;</a></code>
this still isn't a problem &mdash; if an exception is thrown, the
mutex is still unlocked. To get the same behaviour with manual locking
we have to use a <code>catch</code> block, as shown below:</p>

<pre class="listing">
std::mutex m;
std::string s;

void append_with_lock_guard(std::string const&amp; extra)
{
    std::lock_guard&lt;std::mutex&gt; lk(m);
    s+=extra;
}

void append_with_manual_lock(std::string const&amp; extra)
{
    m.lock();
    try
    {
        s+=extra;
        m.unlock();
    }
    catch(...)
    {
        m.unlock();
        throw;
    }
}
</pre>

<p>If you had to do this for every function which might throw an
exception it would quickly get unwieldy. Of course, you still need to
ensure that the code is exception-safe in general &mdash; it's no use
automatically unlocking the mutex if the protected data is left in a
state of disarray.</p>

<h3>Next time</h3>

<p>Next time we'll take a look at the <code><a
href="http://www.stdthread.co.uk/doc/headers/mutex/unique_lock.html">std::unique_lock&lt;&gt;</a></code>
template, which provides more options than <code><a
href="http://www.stdthread.co.uk/doc/headers/mutex/lock_guard.html">std::lock_guard&lt;&gt;</a></code>.</p>

<p><a
href="http://www.justsoftwaresolutions.co.uk/index.rss">Subscribe to
the RSS feed <img class="rss" src="http://www.justsoftwaresolutions.co.uk/images/feed-icon-14x14.png"
alt="RSS feed"></a> for this blog to be sure you don't miss the rest
of the series.</p>

<h3>Multithreading in C++0x Series</h3>

<p>Here are the posts in this series so far:</p>

<ul>

<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></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></li>

<li><a
href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-3.html">Multithreading
in C++0x Part 3: Starting Threads with Member Functions and Reference
Arguments</a></li>

<li><a
href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-4-protecting-shared-data.html">Multithreading
in C++0x Part 4: Protecting Shared Data</a></li>

</ul>
<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/multithreading-in-c++0x-part-4-protecting-shared-data.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++0x" rel="tag">C++0x</a>,  <a href="http://technorati.com/tag/thread" rel="tag">thread</a> <br>  <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fmultithreading-in-c%2B%2B0x-part-4-protecting-shared-data.html&amp;title=Multithreading%20in%20C%2B%2B0x%20part%204%3A%20Protecting%20Shared%20Data"> 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%2Fmultithreading-in-c%2B%2B0x-part-4-protecting-shared-data.html&amp;title=Multithreading%20in%20C%2B%2B0x%20part%204%3A%20Protecting%20Shared%20Data">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%2Fmultithreading-in-c%2B%2B0x-part-4-protecting-shared-data.html&amp;title=Multithreading%20in%20C%2B%2B0x%20part%204%3A%20Protecting%20Shared%20Data">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/multithreading-in-c++0x-part-4-protecting-shared-data.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>March 2009 C++ Standards Committee Mailing - New C++0x Working Paper, Concurrency Changes</title><link>http://www.justsoftwaresolutions.co.uk/cplusplus/cplusplus-standards-committee-mailing-march-2009.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/cplusplus/cplusplus-standards-committee-mailing-march-2009.html</guid><pubDate>Mon, 30 Mar 2009 11:15:13 +0100</pubDate><description><![CDATA[
<p>The March 2009 mailing for the C++ Standards Committee was
published last week. This mailing contains the <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2837.pdf">results
of the first round of National Body voting on the C++0x draft</a>, as
well as the <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2857.pdf">latest
version of the C++0x working draft</a>. This latest draft includes
some changes in response to these NB comments, as agreed at the
committee meeting at the beginning of March. Some of the changes
related to concurrency and the thread library are listed below. The
state of all comments (accepted, rejected, or unprocessed) can be
found in <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2863.html">N2863:
C++ CD1 comment status</a>.</p>

<p>The committee is intending to address all the comments (which may
include rejecting some, as has already happened) in time to publish a
second draft for National Body comments by the end of the year. If
there is sufficient consensus on that draft, it will become the C++0x
standard, otherwise it will have to undergo another round of
revisions.</p>

<h3>Concurrency-related Changes</h3>

<p>The atomics library has only seen one accepted change so far, and
that's a result of US issue 91: a failed compare_exchange operation is
only atomic load rather than a read-modify-write operation.  This
should not have any impact on code that uses atomics, but can enable
the implementation to be optimized on some architectures. The details
can be seen in <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1043">LWG
issue 1043</a>.</p>

<p>On the other hand, the thread library has seen a couple of accepted
changes which <strong>will</strong> have user-visible
consequences. These are:</p>

<dl>
<dt><code>std::thread</code> destructor calls
<code>std::terminate()</code> instead of <code>detach()</code></dt>
<dd>Hans Boehm's paper <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2802.html">N2082:
A plea to reconsider detach-on-destruction for thread objects</a>, was
reviewed as part of US issue 97. The result is that if you do not
explicitly call <code>join()</code> or <code>detach()</code> on your
<code>std::thread</code> objects before they are destroyed then the
library will call <code>std::terminate()</code>. This is to ensure
that there are no unintentional "dangling threads" with references to
local variables.</dd>

<dt><code>std::thread</code> and <code>std::unique_lock</code> no
longer have <code>swap()</code> functions that operate on rvalues</dt>

<dd>This change is in response to US issue 46, and the associated
paper <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2844.html">N2844:
Fixing a Safety Problem with Rvalue References: Proposed Wording
(Revision 1)</a>, which changes the way the rvalue-references work. In
particular, an rvalue-reference no longer binds to an lvalue. Combined
with the previous change to disallow destroying
<code>std::thread</code> objects with an associated thread of
execution this makes perfect sense: swapping two rvalue
<code>std::thread</code> objects serves no purpose anyway, and
swapping a <code>std::thread</code> variable with an rvalue would now
call <code>std::terminate()</code> when the rvalue is destroyed at the
end of the expression, if the variable had an associated thread of
execution.</dd>

<dt>The single-argument <code>std::thread</code> constructor has been
removed</dt>

<dd>This was UK issue 323. The variadic <code>std::thread</code>
constructor provides all the necessary functionality.</dd>

</dl>

<p>There are also a few minor concurrency-related changes that have
been approved, mostly along the lines of clarifying the text. There
are a few more which are still under discussion, one of which is quite
significant: UK issue 329. This comment proposes the addition of a new
function <code>std::async()</code> which will execute a function
asynchronously and return a <code>std::unique_future</code> which can
be used to obtain the result. Details can be seen under <a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1043">LWG
issue 1043</a>.</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/cplusplus-standards-committee-mailing-march-2009.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/C++0x" rel="tag">C++0x</a>,  <a href="http://technorati.com/tag/C++" rel="tag">C++</a>,  <a href="http://technorati.com/tag/standards" rel="tag">standards</a>,  <a href="http://technorati.com/tag/concurrency" rel="tag">concurrency</a> <br>  <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fcplusplus%2Fcplusplus-standards-committee-mailing-march-2009.html&amp;title=March%202009%20C%2B%2B%20Standards%20Committee%20Mailing%20-%20New%20C%2B%2B0x%20Working%20Paper%2C%20Concurrency%20Changes"> 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%2Fcplusplus-standards-committee-mailing-march-2009.html&amp;title=March%202009%20C%2B%2B%20Standards%20Committee%20Mailing%20-%20New%20C%2B%2B0x%20Working%20Paper%2C%20Concurrency%20Changes">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%2Fcplusplus-standards-committee-mailing-march-2009.html&amp;title=March%202009%20C%2B%2B%20Standards%20Committee%20Mailing%20-%20New%20C%2B%2B0x%20Working%20Paper%2C%20Concurrency%20Changes">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/cplusplus-standards-committee-mailing-march-2009.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>The Software Craftsmanship Manifesto</title><link>http://www.justsoftwaresolutions.co.uk/design/software-craftsmanship-manifesto.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/design/software-craftsmanship-manifesto.html</guid><pubDate>Wed, 11 Mar 2009 10:31:04 +0000</pubDate><description><![CDATA[
<p>Do you care about the quality of your work as a software developer?
Do you strive to produce the best software you can for your clients or
employer? I don't mean basic level "does it work?" kind of quality
&mdash; I hope we all aim to produce code that works. Does it matter
to you if the code is well-crafted? Do you strive to write <a
href="http://www.justsoftwaresolutions.co.uk/design/elegance-in-software.html">elegant
software</a>? Do you actively work to improve your skills as a
developer?</p>

<p>There's been a lot of discussion about software quality on the
internet recently. <a href="http://www.objectmentor.com">Uncle
Bob</a>, <a href="http://www.joelonsoftware.com">Joel Spolsky</a> and
<a href="http://www.codinghorror.com">Jeff Atwood</a> got involved in
the <a
href="http://blog.objectmentor.com/articles/2009/01/31/quality-doesnt-matter-that-much-jeff-and-joel">"Quality
doesn't matter"</a> <a
href="http://blog.objectmentor.com/articles/2009/02/06/on-open-letter-to-joel-spolsky-and-jeff-atwood">debate</a>,
culminating in Uncle Bob talking on Jeff and Joel's <a
href="http://blog.stackoverflow.com/2009/02/podcast-41/">Stack
Overflow Podcast</a>. James Bach even went as far as to hypothesise
that <a href="http://www.satisfice.com/blog/archives/224">Quality is
Dead</a>.</p>

<p>James has a point: in many instances it seems that people are quite
happy to tolerate buggy software that's "good enough", and that
developers are quite happy to ship such software. We're not perfect,
and we will write code with bugs in, but to a large extent it's the
attitude that counts. Whilst I accept that there may well be bugs in
my code, I strive to avoid them, work hard to fix any that are found,
and try and learn ways of reducing their occurrence in future. I also
feel that software should be well-crafted so that it doesn't just work
now, but will continue to work as it evolves, and such evolution
should be as easy as possible. Of course, there's more to software
quality than that &mdash; quality is <em>Value to Some Person</em>,
and your job as a software developer is to ensure that your clients,
customers or employers get the things that they value from the
software you develop.</p>

<p>If this is something you feel strongly about, rest assured that
you're not alone &mdash; there are many others who feel that <a
href="http://blog.objectmentor.com/articles/2009/03/07/quality-its-alive-its-alive">Quality
is Alive</a>, to the extent that a few developers have got together to
draft a <a
href="http://manifesto.softwarecraftsmanship.org/main">Manifesto for
Software Craftsmanship</a>. The manifesto has over 1500 signatures
(including mine) &mdash; why not add yours?</p>


<p align="right">Posted by Anthony Williams<br><i>[/  <a href="http://www.justsoftwaresolutions.co.uk/design/">design</a> /] <a href="http://www.justsoftwaresolutions.co.uk/design/software-craftsmanship-manifesto.html">permanent link</a></i><br> <small> Tags:  <a href="http://technorati.com/tag/software" rel="tag">software</a>,  <a href="http://technorati.com/tag/craftsmanship" rel="tag">craftsmanship</a>,  <a href="http://technorati.com/tag/design" rel="tag">design</a>,  <a href="http://technorati.com/tag/manifesto" rel="tag">manifesto</a> <br>  <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fdesign%2Fsoftware-craftsmanship-manifesto.html&amp;title=The%20Software%20Craftsmanship%20Manifesto"> 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%2Fdesign%2Fsoftware-craftsmanship-manifesto.html&amp;title=The%20Software%20Craftsmanship%20Manifesto">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%2Fdesign%2Fsoftware-craftsmanship-manifesto.html&amp;title=The%20Software%20Craftsmanship%20Manifesto">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/design/software-craftsmanship-manifesto.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>Multithreading in C++0x part 3: Starting Threads with Member Functions and Reference Arguments</title><link>http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-3.html</link><author>Anthony Williams</author><guid isPermaLink="true">http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-3.html</guid><pubDate>Thu, 26 Feb 2009 00:00:00 +0000</pubDate><description><![CDATA[
<p><em>This is the third of a series of blog posts introducing the new
C++0x thread library. The first two parts covered <a
href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-C++0x-part-1-starting-threads.html">Starting
Threads in C++0x</a> with simple functions, and starting threads with
<a
href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-C++0x-part-2-function-objects-and-arguments.html">function
objects and additional arguments</a>.</em></p>

<p>If you've read the previous parts of the series then you've seen
how to start threads with functions and function objects, with and
without additional arguments. However, the function objects and
arguments are always copied into the thread's internal storage. What
if you wish to run a member function other than the function call
operator, or pass a reference to an existing object?</p>

<p>The C++0x library can handle both these cases: the use of member
functions with <code><a
href="http://www.stdthread.co.uk/doc/headers/thread/thread.html">std::thread</a></code>
requires an additional argument for the object on which to invoke the
member function, and references are handled with
<code>std::ref</code>. Let's take a look at some examples.</p>

<h3>Invoking a member function on a new thread</h3>

<p>Starting a new thread which runs a member function of an existing
object: you just pass a pointer to the member function and a value to
use as the <code>this</code> pointer for the object in to the <code><a
href="http://www.stdthread.co.uk/doc/headers/thread/thread.html">std::thread</a></code>
constructor.</p>

<pre class="listing">
#include &lt;thread&gt;
#include &lt;iostream&gt;

class SayHello
{
public:
    void greeting() const
    {
        std::cout&lt;&lt;"hello"&lt;&lt;std::endl;
    }
};

int main()
{
    SayHello x;
    std::thread t(&amp;SayHello::greeting,&amp;x);
    t.join();
}
</pre>

<p>You can of course pass additional arguments to the member function
too:</p>

<pre class="listing">
#include &lt;thread&gt;
#include &lt;iostream&gt;

class SayHello
{
public:
    void greeting(std::string const&amp; message) const
    {
        std::cout&lt;&lt;message&lt;&lt;std::endl;
    }
};

int main()
{
    SayHello x;
    std::thread t(&amp;SayHello::greeting,&amp;x,"goodbye");
    t.join();
}
</pre>

<p>Now, the preceding examples both a plain pointer to a local object
for the <code>this</code> argument; if you're going to do that, you
need to ensure that the object outlives the thread, otherwise there
will be trouble. An alternative is to use a heap-allocated object and
a reference-counted pointer such as
<code>std::shared_ptr&lt;SayHello&gt;</code> to ensure that the object
stays around as long as the thread does:</p>

<pre class="listing">
#include &lt;&gt;

int main()
{
    std::shared_ptr&lt;SayHello&gt; p(new SayHello);
    std::thread t(&amp;SayHello::greeting,p,"goodbye");
    t.join();
}
</pre>

<p>So far, everything we've looked at has involved copying the
arguments and thread functions into the internal storage of a thread
even if those arguments are pointers, as in the <code>this</code>
pointers for the member functions. What if you want to pass in a
<em>reference</em> to an existing object, and a pointer just won't do?
That is the task of <code>std::ref</code>.</p>

<h3>Passing function objects and arguments to a thread by
reference</h3>

<p>Suppose you have an object that implements the function call
operator, and you wish to invoke it on a new thread. The thing is you
want to invoke the function call operator on <em>this particular
object</em> rather than copying it. You could use the member function
support to call <code>operator()</code> explicitly, but that seems a
bit of a mess given that it <em>is</em> callable already. This is the
first instance in which <code>std::ref</code> can help &mdash; if
<code>x</code> is a callable object, then <code>std::ref(x)</code> is
too, so we can pass <code>std::ref(x)</code> as our function when we
start the thread, as below:</p>

<pre class="listing">
#include &lt;thread&gt;
#include &lt;iostream&gt;
#include &lt;functional&gt; // for std::ref

class PrintThis
{
public:
    void operator()() const
    {
        std::cout&lt;&lt;"this="&lt;&lt;this&lt;&lt;std::endl;
    }
};

int main()
{
    PrintThis x;
    x();
    std::thread t(std::ref(x));
    t.join();
    std::thread t2(x);
    t2.join();
}
</pre>

<p>In this case, the function call operator just prints the address of
the object. The exact form and values of the output will vary, but the
principle is the same: this little program should output three
lines. The first two should be the same, whilst the third is
different, as it invokes the function call operator on a <em>copy</em>
of <code>x</code>. For one run on my system it printed the following:</p>

<pre class="listing">
this=0x7fffb08bf7ef
this=0x7fffb08bf7ef
this=0x42674098
</pre>

<p>Of course, <code>std::ref</code> can be used for other arguments
too &mdash; the following code will print "x=43":</p>

<pre class="listing">
#include &lt;thread&gt;
#include &lt;iostream&gt;
#include &lt;functional&gt;

void increment(int&amp; i)
{
    ++i;
}

int main()
{
    int x=42;
    std::thread t(increment,std::ref(x));
    t.join();
    std::cout&lt;&lt;"x="&lt;&lt;x&lt;&lt;std::endl;
}
</pre>

<p>When passing in references like this (or pointers for that matter),
you need to be careful not only that the referenced object outlives
the thread, but also that appropriate synchronization is used. In this
case it is fine, because we only access <code>x</code> before we start
the thread and after it is done, but concurrent access would need
protection with a mutex.</p>

<h3>Next time</h3>

<p>That wraps up all the variations on starting threads; next time
we'll look at using mutexes to protect data from concurrent
modification.</p>

<p><a
href="http://www.justsoftwaresolutions.co.uk/index.rss">Subscribe to
the RSS feed <img class="rss" src="http://www.justsoftwaresolutions.co.uk/images/feed-icon-14x14.png"
alt="RSS feed"></a> for this blog to be sure you don't miss the rest
of the series.</p>

<h3>Multithreading in C++0x Series</h3>

<p>Here are the posts in this series so far:</p>

<ul>

<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></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></li>

<li><a
href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-3.html">Multithreading
in C++0x Part 3: Starting Threads with Member Functions and Reference
Arguments</a></li>

<li><a
href="http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-4-protecting-shared-data.html">Multithreading
in C++0x Part 4: Protecting Shared Data</a></li>

</ul>
<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/multithreading-in-c++0x-part-3.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++0x" rel="tag">C++0x</a>,  <a href="http://technorati.com/tag/thread" rel="tag">thread</a> <br>  <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.justsoftwaresolutions.co.uk%2Fthreading%2Fmultithreading-in-c%2B%2B0x-part-3.html&amp;title=Multithreading%20in%20C%2B%2B0x%20part%203%3A%20Starting%20Threads%20with%20Member%20Functions%20and%20Reference%20Arguments"> 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%2Fmultithreading-in-c%2B%2B0x-part-3.html&amp;title=Multithreading%20in%20C%2B%2B0x%20part%203%3A%20Starting%20Threads%20with%20Member%20Functions%20and%20Reference%20Arguments">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%2Fmultithreading-in-c%2B%2B0x-part-3.html&amp;title=Multithreading%20in%20C%2B%2B0x%20part%203%3A%20Starting%20Threads%20with%20Member%20Functions%20and%20Reference%20Arguments">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/multithreading-in-c++0x-part-3.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>