    <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++ (Part 2)</title>
        <link>https://members.accu.org/index.php/articles/498</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 #36 - Mar 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/c168/">36</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+168/">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++ (Part 2)</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 March 2000 17:50:56 +01:00 or Sun, 26 March 2000 17:50:56 +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>The first part of this series of articles on threads addressed
what I called the function signature mismatch problem. The thread
library needs to allow an arbitrary user-defined function to be run
asynchronously with respect to other threads. That function could
have any number of parameters of any type, but the thread library
can only accept a function (or function object) with a simple,
fixed interface.</p>
<p>My solution to this first design challenge was called
<span class="bold"><b>Thread-Runs-Polymorphic-Object</b></span>.
The key feature of this design is that the thread management
facilities provided by a suitable library are separated from the
application-specific code. This is achieved by having both a
concrete thread class and an abstract thread function class. The
thread class defines the thread management facilities provided by
the library and the thread function class defines a function object
interface for the library's users.</p>
<div class="sidebar">
<p class="title c2">Figure 1 - Thread-Runs-Polymorphic-Object</p>
<pre class="programlisting">
// thread management facilities
class thread
{
public:
  struct function;
  thread (function&amp;);
  . . .
};

// interface for application-specific code
struct thread::function
{
  virtual ~function() {}
  virtual int run() = 0;
};
</pre></div>
<p>In this instalment I would like to present a fairly complete
implementation of a thread library based on the ideas presented in
these articles. First, though, there is another design issue to
address.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e34" id="d0e34"></a>The Second
Design Challenge</h2>
</div>
<p>Figure 2 shows the sample code in the previous article fleshed
out to an almost complete program. The <tt class=
"function">main()</tt> function creates a new thread, uses the
child thread to print a file, performs some other processing in the
main thread, waits for the child thread to terminate and exits.</p>
<div class="sidebar">
<p class="title c2">Figure 2a - Background printing example.</p>
<pre class="programlisting">
#include &quot;thread.h&quot;
#include &quot;printer.h&quot;

// concrete thread function class
class print_function : public thread::function
{
public:
  print_function (Printer&amp; p, std::string n)
    : printer(p), file_name(n) {}
</pre></div>
<div class="sidebar">
<p class="title c2">Figure 2b - Background printing example
(cont).</p>
<pre class="programlisting">
private:
  virtual int run()
  {
    printer.print(file_name);
    return 0;
  }
  Printer&amp;    printer;
  std::string file_name;
};

int main()
{
// Start printing in the background.
  Epson_Stylus printer;
  std::string  file_name(&quot;printer_test.txt&quot;);
  print_function print_file(printer,file_name);
  thread print_thread(print_function);

// Execute some foreground actions...

// Wait for the background thread to finish.

  print_thread.wait();

  return 0;
}
</pre></div>
<p>Note that the main thread creates, stores and destroys the
thread object representing the child thread. But what if the
<tt class="function">main()</tt> function were to return before the
child thread has finished? If the thread object truly represents a
thread of execution, destroying the thread object should terminate
the child thread. This makes it difficult to support designs in
which the child outlives its parent (Posix detached threads, for
example).</p>
<p>Of course, the parent thread could create the thread object on
the heap and throw away the pointer. But some thread must still
destroy the orphaned child - otherwise we have a memory leak. The
child can not destroy its own thread object because, in general, it
will not know if some other thread is about to use that object to
change its priority or read its termination status, perhaps. In
fact, no thread can take sole responsibility for destroying the
child's thread object for exactly the same reason - some other
thread could be about to use the thread object.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e59" id=
"d0e59"></a>Reference-Counting</h2>
</div>
<p>What we need is shared responsibility. The last thread that
needs to access the orphaned child's thread object should destroy
it. Regular readers of Overload will, no doubt, recognise this
problem. The tried and tested solution is the <span class=
"bold"><b>Handle-and-Reference-Counted-Body</b></span> design
pattern. The handle part of this pattern is an example of a smart
pointer; the overall pattern is a particular case of the
<span class="bold"><b>Proxy</b></span> pattern [<a href=
"#GoF">GoF</a>].</p>
<p>James Coplien has catalogued several variations on the
Handle/Body pattern [<a href="#EuroPLoP">EuroPLoP</a>] and Scott
Meyers describes smart pointers and reference counting in <i class=
"citetitle">More Effective C++</i> [<a href=
"#Meyers">Meyers</a>].</p>
<p>The skeleton C++ code in Figure 3 through Figure 5 shows one way
of implementing this reference-counting technique. For another
approach see the Boost Website [<a href="#boost">boost</a>].</p>
<div class="sidebar">
<p class="title c2">Figure 3 - Reference-Counted Body</p>
<pre class="programlisting">
// A thread body with shared ownership
class body
{
public:
  body(function&amp;);
  friend class handle;
// ... thread functions ...
private:
  unsigned handle_count;
};

body::body (function&amp; fn)
    : handle_count(0)
{
//... create a thread ...
}
</pre></div>
<p>In this case, the body class represents a thread that executes
the function object passed to its constructor. I have provided both
public and private members to show separate interface and
implementation sections; in practice, though, the body class is
entirely hidden from client code.</p>
<p>The handle class creates, destroys and performs all operations
on body objects. Client code performs thread operations indirectly
via a suitable handle. And, since I have made handle a friend of
body, the body class need not have any public methods at all.</p>
<div class="sidebar">
<p class="title c2">Figure 4 - Handle Interface</p>
<pre class="programlisting">
// A thread handle that shares ownership
// of a 'body'
class handle {
public:
  handle(function&amp;);
  ~handle() throw();

  handle (const handle&amp;);
  handle&amp; operator= (const handle&amp;);

// ... thread functions ...

private:
  body* shared_body;
};
</pre></div>
<p>A <tt class="classname">handle</tt> is a small object with
'value' semantics. That is, it can be created, copied and destroyed
using the same syntax as the built-in types. It is intended to be
passed to functions by value.</p>
<p>I have chosen to make the <tt class="classname">handle</tt>
class a true Proxy in that all operations on threads are provided
through forwarding member functions of <tt class=
"classname">handle</tt>. These are not shown here; they will be
described later.</p>
<p>Each <tt class="classname">handle</tt> points to a <tt class=
"classname">body</tt> and the <tt class="classname">body</tt> holds
a count of the number of <tt class="classname">handle</tt>s
pointing to it. When a new <tt class="classname">handle</tt> is
created the <tt class="classname">body</tt>'s <tt class=
"classname">handle</tt> <tt class="varname">count</tt> is
incremented; when a <tt class="classname">handle</tt> is destroyed
the <tt class="classname">body</tt>'s <tt class=
"classname">handle</tt> <tt class="varname">count</tt> is
decremented. When the last <tt class="classname">handle</tt> is
destroyed the <tt class="classname">body</tt> is destroyed,
too.</p>
<div class="sidebar">
<p class="title c2">Figure 5 - Handle Implementation</p>
<pre class="programlisting">
handle::handle(function&amp; fn)
            : shared_body(new body(fn))
{
  ++shared_body-&gt;handle_count;
}
handle::~handle() throw()
{
  if (--shared_body-&gt;handle_count == 0)
    delete shared_body;
}
handle::handle (const handle&amp; old_handle)
  : shared_body(old_handle.shared_body)
{
  ++shared_body-&gt;handle_count;
}
handle&amp; handle::operator= 
            (const handle&amp; other_handle)
{
  this-&gt;~handle();
  new(this) handle(other_handle);
  return *this;
}
</pre></div>
<p>The <tt class="classname">handle</tt>'s primary constructor
creates a <tt class="classname">body</tt> on the heap (passing a
function object) and increments the <tt class=
"classname">handle</tt> <tt class="varname">count</tt>. Thus, a
single operation creates both a <tt class="classname">body</tt> and
its first <tt class="classname">handle</tt>. The <tt class=
"classname">handle</tt>'s destructor decrements the <tt class=
"classname">body</tt>'s <tt class="classname">handle</tt>
<tt class="varname">count</tt> and, if the <tt class=
"varname">count</tt> becomes zero, destroys the body.</p>
<p>The <tt class="classname">handle</tt>'s copy constructor
increments the <tt class="classname">body</tt>'s <tt class=
"classname">handle</tt> <tt class="varname">count</tt>. The
assignment operator literally destroys the existing <tt class=
"classname">handle</tt> and creates a new one that is a copy of the
<tt class="classname">handle</tt> on the right hand side of the
assignment expression. If the use of the destructor and placement
<tt class="literal">new</tt> offends you, these can be replaced by
auxiliary functions (<tt class="function">destroy()</tt> and
<tt class="function">create()</tt>, perhaps).</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e229" id="d0e229"></a>Thread
Priorities</h2>
</div>
<p>When designing a library component it is often difficult to
reconcile the need for a simple generic interface with the desire
to provide the full power of the underlying operating system.
Thread priority schemes provide a simple example. All the thread
libraries I've looked at use integers to represent thread
priorities, but the <tt class="type">int</tt> type is
platform-dependent and there is no guarantee that all integer
values are valid thread priorities. Under Win32, for example, there
are only seven valid values for the priority parameter of the
<tt class="function">SetThreadPriority()</tt> API call. So, how can
we make it possible for our thread library to use the much wider
range of priorities available under Posix and real-time operating
systems, while preventing the user from specifying invalid values
under Win32?</p>
<p>I know of no general solution to these kinds of problem, but
there is often a particular solution in individual cases. I usually
try to generalise the problem first and look for a solution to the
general problem. If that works we are home and dry. In this case,
the right question to ask seems to be, &quot;why do we have
priorities?&quot;. And the answer has to be, &quot;to control the scheduling
algorithm&quot;. So, if we could provide our own scheduling algorithm it
would be possible to achieve complete control of our threads.
Unfortunately, operating systems don't usually provide that sort of
hook, so I quickly abandoned the idea of overriding the operating
system's built-in scheduler.</p>
<p>On the other hand, with suspend and resume functions we can take
control of our threads. The operating system may still interfere to
some extent (Win32 applies a dynamic boost at times, for example),
but in principle these simple functions allow us to control the
length of a time-slice, the proportion of CPU time allocated to
individual threads, and so on. We can write our own scheduler,
although such a scheduler is likely to be rather crude and
inefficient compared with the operating system's native
scheduler.</p>
<p>So it seems to me that a thread library needs to provide suspend
and resume functions for special scheduling needs and priority
control functions for the normal case, in which the operating
system uses a thread's priority as a parameter to its internal
scheduling algorithm. This brings us back to priority values. If
the valid values are defined by the operating system's scheduler,
how can we support priorities in a platform-independent thread
library?</p>
<p>The best answer I can come up with is to define
platform-dependent constants for the default, minimum and maximum
priority values. It is possible for the library to provide
platform-independent access to these values. Applications with
stringent requirements for thread priorities would need to have a
flexible strategy in order to maintain platform-independence. Less
fussy applications can use a small set of priority values or simply
accept being restricted to particular platforms.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e248" id="d0e248"></a>Thread
Library Interface</h2>
</div>
<p>Putting it all together, here is my initial vision of a thread
library suitable for use in standard-conforming programs. Figure 6
shows the <tt class="literal">thread namespace</tt>, Figure 7 shows
the <tt class="classname">thread function</tt> class and Figure 8
shows the <tt class="classname">thread handle</tt> class. The
definition of the <tt class="classname">thread body</tt> class is
part of the implementation and is of no concern to the user of the
library.</p>
<div class="sidebar">
<p class="title c2">Figure 6 - The Thread Namespace</p>
<pre class="programlisting">
namespace thread {
  class handle;
  class body;
  struct function;
  typedef std::string name_type;
  typedef int priority_type;
  extern const priority_type minimum_priority;
  extern const priority_type default_priority;
  extern const priority_type maximum_priority;
  void sleep (unsigned long mS);
}
</pre></div>
<p>The thread namespace declares some types, some constants and one
global function. These are all natural candidates for a namespace.
Note, however, that there is no thread class, which seems a bit
odd. I did consider re-naming <tt class="classname">handle</tt> as
'thread', but I felt that 'handle' was better because it strongly
suggests a small, value-like object and there may be many handles
to a single thread. A better case could be made for re-naming
<tt class="classname">body</tt>, but I still like <tt class=
"classname">thread::body</tt> rather than <tt class=
"classname">thread::thread</tt>.</p>
<p>The global function is topical. The current issue of the
<i class="citetitle">C/C++ Users Journal</i> [<a href=
"#Journal">Journal</a>] carries an article by Scott Meyers in which
he argues that encapsulation is enhanced by using global functions
rather than <tt class="literal">static</tt> member functions when
there is a choice. This surprised some readers and triggered a
debate on the <tt class="literal">accu-general</tt> e-mail list. My
reason for choosing a global function here is more mundane - I
believe users would find <tt class=
"literal">thread::sleep(1000)</tt> more intuitive than <tt class=
"literal">thread::handle::sleep(1000)</tt>. However, I might as
well claim that it also provides greater encapsulation - it might
earn me extra Brownie points :)</p>
<div class="sidebar">
<p class="title c2">Figure 7 - The Thread Function Interface
Class</p>
<pre class="programlisting">
struct thread::function {
  virtual ~function() {}
  virtual int operator() () = 0;
};
</pre></div>
<p>As discussed in the previous article, the <tt class=
"classname">thread function</tt> class defines a function object
interface. Application code is required to define a derived class
that implements the function call operator, create an object of the
concrete type and pass it to the thread library. It is up to the
library to create a new thread which will execute the code in the
user-defined <tt class="methodname">operator()</tt> function.</p>
<div class="sidebar">
<p class="title c2">Figure 8 - The Thread Handle Class</p>
<pre class="programlisting">
class thread::handle {
public:
  handle (function&amp;);
  handle ();
   ~handle () throw();
  handle (const handle&amp;);
  handle&amp; operator= (const handle&amp;);
  void start();
  void wait();
  int status() const;
  name_type name() const;
  void set_name (name_type);
  priority_type priority() const;
  void set_priority (priority_type);
  void suspend();
  void resume();
private:
  body* shared_body;
};
</pre></div>
<p>The <tt class="classname">thread::handle</tt> class defines most
of the interface supported by the thread library. Note that there
are no platform-specific items in the class declaration, so no
platform-specific header is needed.</p>
<p>The default constructor is used to create a handle to the
current thread. This <tt class="classname">handle</tt> can be used
to get and set the attributes of the current thread and can be used
by other threads just like any other handle. The other
constructors, destructor and assignment operator were discussed
earlier. Together this group of functions manages the reference
counting.</p>
<p>Threads are created in the suspended state so that their
attributes can be set before the thread function starts. The
<tt class="function">start()</tt> function starts the thread
function in the same way that <tt class="function">resume()</tt>
re-starts the thread function. In fact, in my Win32 implementation,
<tt class="function">start()</tt> and <tt class=
"function">resume()</tt> are identical. The <tt class=
"function">wait()</tt> function suspends the current thread until
the thread associated with the handle has terminated. The
<tt class="function">status()</tt> function returns the termination
status of the target thread.</p>
<p>Named threads are unusual, but Java threads have names and we
created something similar at work. I have included names because
they seem to be useful for diagnostics, particularly when an
exception has been thrown and the application code has failed to
catch it. (This is a bug, of course, but we realise that we are not
perfect.) The thread library has get and set functions for the
thread name. By default the name is the empty string.</p>
<p>The other attribute provided by the thread library is a
priority. There are get and set functions for the priority. As
mentioned earlier, the thread namespace defines minimum, maximum
and default priority values.</p>
<p>Finally, there are the <tt class="function">suspend()</tt> and
<tt class="function">resume()</tt> functions that are intended for
application-defined scheduling policies. I have tentatively chosen
the simplest possible interface for these functions, but there may
be better options. Under Win32 the <tt class=
"function">suspend</tt> and <tt class="function">resume</tt>
functions respectively increment and decrement a suspend count. The
thread is suspended if the suspend count is greater than zero. Both
functions return the previous suspend count (if they succeed). As
yet I have been unable to find a compelling reason for providing
such behaviour, but I'm sure the Win32 designers knew what they
were doing.</p>
<p>The library reports errors by throwing standard <tt class=
"exceptionname">runtime_error</tt> exceptions. In the current
implementation the message string contains the name of the thread,
the name of the function that failed and a message obtained from
the operating system describing the reason for the failure.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e375" id="d0e375"></a>Taking
Stock</h2>
</div>
<p>The thread library presented here provides most of the 'core'
facilities listed in the previous article. Although it would be
possible to provide a means for terminating the thread function I
see this as a job for the application rather than the library. A
'suspend until ...' function would be a useful addition, but this
takes us beyond threads into the realms of other kinds of &quot;waitable
object&quot; as Win32 calls them.</p>
<p>Although not included in my original list of core facilities,
the library should also provide thread synchronisation mechanisms
such as mutexes, critical sections, and scoped lock objects. Apart
from these, the most important remaining omission is, perhaps,
access control facilities. This is a topic in itself and it's not
something I know much about, so I will not address it here.</p>
<p>So far, I have described a <span class=
"bold"><b>Thread-Runs-Polymorphic-Object</b></span> model in which
a thread object executes a function object just once. Our
experience at work suggests that this model is not quite as easy to
use as we had expected. In the next and final article in this
series I would like to look at ease-of-use issues and propose a
more application-oriented threading model in which a thread
executes a sequence of function objects. In the meantime, I would
welcome your comments.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e387" id="d0e387"></a>References</h2>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] &quot;<span class="citetitle"><i class=
"citetitle">Design Patterns - Elements of Reusable Object-Oriented
Software</i></span>&quot;, by Erich Gamma, Richard Helm, Ralph Johnson
and John Vlissides, ISBN 0-201-63361-2.</p>
</div>
<div class="bibliomixed"><a name="EuroPLoP" id="EuroPLoP"></a>
<p class="bibliomixed">[EuroPLoP] <span class="bibliomisc"><a href=
"http://www.bell-labs.com/user/cope/%20Patterns/C++Idioms/EuroPLoP98.html"
target="_top">http://www.bell-labs.com/user/cope/
Patterns/C++Idioms/EuroPLoP98.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Meyers" id="Meyers"></a>
<p class="bibliomixed">[Meyers] <span class="citetitle"><i class=
"citetitle">More Effective C++</i></span>, by Scott Meyers, ISBN
0-201-63371-X.</p>
</div>
<div class="bibliomixed"><a name="boost" id="boost"></a>
<p class="bibliomixed">[boost] <span class="bibliomisc"><a href=
"http://www.boost.org" target=
"_top">http://www.boost.org</a></span>.</p>
</div>
<div class="bibliomixed"><a name="Journal" id="Journal"></a>
<p class="bibliomixed">[Journal] <span class="citetitle"><i class=
"citetitle">C/C++ Users Journal</i></span>, February 2000.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
