    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Supporting Threads in Standard C++ (Addendum)</title>
        <link>https://members.accu.org/index.php/articles/484</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #38 - Jul 2000</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c166/">38</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-166/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+166/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Supporting Threads in Standard C++ (Addendum)</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 July 2000 17:50:58 +01:00 or Wed, 26 July 2000 17:50:58 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>During a conversation at the March Java and C/C++ Conference I
promised not to inflict another article about threads on Overload
readers. It is time to move on to other topics. However, Kevlin
Henney raised some issues that are well worth discussing. So,
please bear with me one more time. I shall be brief.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a>Bugs</h2>
</div>
<p>In Part 2 I presented a thread handle class with an assignment
operator implemented by destroying and re-constructing the handle
object. This is <span class="bold"><b>not</b></span> a good idea.
Kevlin tells me that the reasons are explained in Herb Sutter's
book, <i class="citetitle">Exceptional C++</i> [<a href=
"#Sutter">Sutter</a>], and in <i class="citetitle">Ruminations on
C++</i> [<a href="#Koenig-">Koenig-</a>] by Andrew Koenig and
Barbara Moo. I have not yet been able to consult <i class=
"citetitle">Ruminations</i>, but Herb's <i class="citetitle">Guru
of the Week</i> item entitled <i class="citetitle">Object Lifetimes
- Part I</i> makes three points about this technique:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>The technique works except...</p>
</li>
<li>
<p>... when the constructor can throw an exception or ...</p>
</li>
<li>
<p>... the class is used as a base class.</p>
</li>
</ol>
</div>
<p>(You will find this under item 22 on the PeerDirect Web site
[<a href="#peerdirect">peerdirect</a>] or item 40 in <i class=
"citetitle">Exceptional C++</i>.)</p>
<p>I will say in my defence that my handle's copy constructor does
not throw exceptions and the handle class was not intended to be
used as a base class. Nevertheless, as Herb puts it, this is a &quot;bad
habit&quot;.</p>
<p>Here is a better implementation of the thread handle class from
the earlier article.</p>
<div class="sidebar">
<p class="title c2">Figure 1 - Handle Interface.</p>
<pre class="programlisting">
// A thread handle that shares ownership 
// of a 'body'
class handle 
{
public:
// The default four

  handle(function&amp;);
  ~handle() throw();

  handle (const handle&amp;);
  handle&amp; operator= (const handle&amp;);

// ... thread functions ...
private:
  void attach (body*);
  void detach () throw();

  body* shared_body;
};
</pre></div>
<div class="sidebar">
<p class="title c2">Figure 2 - Handle Implementation.</p>
<pre class="programlisting">
inline void handle::attach 
                    (body* new_body){
  shared_body = new_body;
  ++shared_body-&gt;handle_count;
}

inline void handle::detach() throw(){
  if (-shared_body-&gt;handle_count == 0)
    delete shared_body;
}

handle::handle (function&amp; fn) 
          {attach(new body(fn));}

handle::~handle() throw() {detach();}

thread::handle::handle 
          (const handle&amp; old_handle){
  attach(old_handle.shared_body);
}

handle&amp; handle::operator= 
          (const handle&amp; other_handle){
  detach();
  attach(other_handle.shared_body);

  return *this;
}
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e83" id=
"d0e83"></a>Improvements</h2>
</div>
<p>Kevlin also suggested a mechanism to make the thread library
more general and easier to use. The idea is to provide the thread
handle class with a template constructor.</p>
<div class="sidebar">
<p class="title c2">Figure 3 - Thread handle class with template
constructor.</p>
<pre class="programlisting">
class thread::handle
{
public:
  template &lt;typename function&gt; 
    handle (function);
  . . .
};
</pre></div>
<p>Client code can run any suitable function or function object in
a separate thread by passing it to this constructor. In this case,
a &quot;suitable&quot; object is one that satisfies the following
requirement:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>Given an object, <tt class="literal">fn</tt>, the expression
<tt class="type">fn()</tt> must be well formed and of type
<tt class="type">int</tt>.</p>
</blockquote>
</div>
<p>In particular, the <tt class="literal">fn</tt> object may be a
pointer to a non-member function, a pointer to a static member
function or any function object with an <tt class="methodname">int
operator()()</tt> member. Note that suitable function objects do
not have to be derived from <tt class=
"classname">thread::function</tt>.</p>
<p>So, for example, these code fragments are valid:</p>
<div class="sidebar">
<p class="title c2">Example 3: function object</p>
<pre class="programlisting">
// Example 1: non-member function
int some_function();

int main(){
  thread::handle handle(some_function);
}
// Example 2: static member function
struct some_class {
  static int some_function();
};

int main() {
  thread::handle 
  handle(some_class::some_function);
}
</pre></div>
<div class="sidebar">
<p class="title c2">Figure 4 - Using the template constructor.</p>
<pre class="programlisting">
struct function_object {
  int operator()();
};

function_object some_function_object;

int main() {
  thread::handle handle(some_function_object);
}
</pre></div>
<p>I had intended to include a template constructor in the sample
code I presented in Part 2 of this series of articles. This was to
be my alternative to Allan Kelly's class template design [<a href=
"#Kelly31">Kelly31</a>], [<a href="#Kelly33">Kelly33</a>].
Unfortunately, I discovered lots of other issues along the way and
left myself no time to work out how to implement the template
constructor. So, when Kevlin suggested using the External
Polymorphism pattern, I had no excuse for leaving this loose end
untied. This was, after all, the reason for starting these articles
in the first place.</p>
<p>The External Polymorphism design pattern describes a hierarchy
of polymorphic classes whose behaviour is determined by non-virtual
functions. It is particularly appropriate here because my thread
implementation relies on polymorphic function objects derived from
the thread::function class, but the behaviour of these function
objects may be provided by non-member functions or non-virtual
function call operators.</p>
<p>The key to the External Polymorphism pattern is the generation
of adapter classes for each non-virtual function. For the thread
library these will be function adapters and they can be
conveniently defined by a single class template, as shown in Figure
5. In this case I have reverted to the more usual method of storing
the function-like object by value instead of by reference.</p>
<p>The External Polymorphism approach does have one drawback -
rather more scaffolding is needed to ensure that the thread
implementation is hidden from clients. The extra complexity arises
because the definition of the template constructor must be
available at the point of use, i.e. in the client code. In this
case, the handle's constructor implementation creates the function
adapter. Since this is also a template, its definition must also be
available at the point of use. But, if we wish to hide the
platform-specific parts of the implementation, the class that
encapsulates them must remain an incomplete type in the header
file. So the implementation details must be split across two
classes (<tt class="classname">body</tt> and <tt class=
"classname">function_adapter&lt;F&gt;</tt>) instead of one.</p>
<div class="sidebar">
<p class="title c2">Figure 5 - The template constructor
implementation.</p>
<pre class="programlisting">
// thread.h
namespace thread  {
  struct function;
  template &lt;typename F&gt; 
    class function_adapter;
  class handle;
  class body;
}

struct thread::function {
  virtual ~function() {}
  virtual int operator() () = 0;
};

template &lt;typename F&gt;
  class thread::function_adapter 
            : public thread::function {
public:
  function_adapter (F f) : fn(f) {}
  virtual int operator()() {return fn();}
private:
  F fn;
};

class thread::handle {
public:
  template &lt;typename function&gt;
    handle (function);
  . . .
private:
  body* make_body (thread::function*);
  body* shared_body;
};

template &lt;typename function&gt;
  thread::handle::handle (function fn)
  : shared_body(make_body(new
     function_adapter&lt;function&gt;(fn))){}
</pre></div>
<p>Hiding the platform-specific implementation details also makes
it necessary to use an auxiliary function (<tt class=
"function">make_body</tt>) to create the thread body.</p>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e160" id="d0e160"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Sutter" id="Sutter"></a>
<p class="bibliomixed">[Sutter] <span class="citetitle"><i class=
"citetitle">Exceptional C++</i></span> by Herb Sutter, ISBN
0-201-61562-2.</p>
</div>
<div class="bibliomixed"><a name="Koenig-" id="Koenig-"></a>
<p class="bibliomixed">[Koenig-] <span class="citetitle"><i class=
"citetitle">Ruminations on C++</i></span> by Andrew Koenig and
Barbara Moo, ISBN 0-201-42339-1.</p>
</div>
<div class="bibliomixed"><a name="peerdirect" id="peerdirect"></a>
<p class="bibliomixed">[peerdirect] <span class=
"bibliomisc"><a href="http://www.peerdirect.com" target=
"_top">http://www.peerdirect.com</a></span></p>
</div>
<div class="bibliomixed"><a name="Kelly31" id="Kelly31"></a>
<p class="bibliomixed">[Kelly31] <span class="citetitle"><i class=
"citetitle">Overload, No. 31</i></span>, April 1999, Using
Templates to Handle Multi-threading by Allan Kelly.</p>
</div>
<div class="bibliomixed"><a name="Kelly33" id="Kelly33"></a>
<p class="bibliomixed">[Kelly33] <span class="citetitle"><i class=
"citetitle">Overload, No. 33</i></span>, August 1999, More
Threading with Templates by Allan Kelly.</p>
</div>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
