    <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 3)</title>
        <link>https://members.accu.org/index.php/journals/490</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>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #37 - May 2000 + Programming Topics</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/journals/">All</a>

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c167/">37</a>
                    (7)
<br />

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

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

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

                                            <a href="https://members.accu.org/index.php/journals/c167-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c167+65/">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 3)</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 May 2000 17:50:57 +01:00 or Fri, 26 May 2000 17:50:57 +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>Recap</h2>
</div>
<p>The previous articles in this series on threads offered two
suggestions:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Use a thread function interface class to separate the
application-specific code from the thread library facilities (the
<i class="firstterm">Thread-Runs-Polymorphic-Object</i>
design).</p>
</li>
<li>
<p>Use a <i class="firstterm">Handle-and-Reference-Counted-Body</i>
technique to manage the lifetime of objects representing
threads.</p>
</li>
</ul>
</div>
<p>The resulting thread model can form the basis of a useful thread
library. In practice, however, it does not address some
problems.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e38" id="d0e38"></a>Active
Objects</h2>
</div>
<p>At the heart of the project I have been working on for the past
two years there are active objects known as Jobs. There are several
different kinds of Job and each runs in its own thread. Roughly
speaking, a Top Job runs Middle Jobs and a Middle Job runs Bottom
Jobs. (I have changed the names to protect the innocent.)</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>So, naturalists observe, a flea hath smaller fleas that on him
prey; and these have smaller fleas to bite 'em, and so proceed ad
infinitum. (Jonathan Swift)</p>
</blockquote>
</div>
<div class="sidebar">
<p class="title c2">Figure 1 - Job class structure.</p>
<pre class="programlisting">
// A 2-step Job.
class Job : public Thread::Function {
public:
  Job() : thread(0), done(false) {}
  ~Job() {delete thread;}
  void Start();
  void Step1_Completed();
  void Step2_Completed();
  void Wait() const {thread-&gt;wait();}
  . . .
private:
  class Command;
  virtual int Run();
// implement Thread::Function::Run()
  void Start_Step1();
  void Start_Step2();
  void Terminate() {done = true;}
  Thread* thread;
  Queue   command_queue;
  bool  done;
};
void Job::Start() {
  thread = new Thread(*this);
  command_queue.Put(new Command(this,
                &amp;Job::Start_Step1));
}
void Job::Step1_Completed() {
  command_queue.Put(new Command(this,
                 &amp;Job::Start_Step2));
}
void Job::Step2_Completed() {
  command_queue.Put(new Command(this,
                 &amp;Job::Terminate));
}
</pre></div>
<p>Each Job class hides its thread behind a suitable interface, as
shown in Figure 1. The thread model is essentially the same as the
<span class=
"emphasis"><em>Thread-Runs-Polymorphic-Object</em></span> design
described in the previous articles.</p>
<p>Each Job contains a queue of <span class=
"emphasis"><em>Command</em></span> objects [<a href=
"#GoF">GoF</a>]. Public member functions add commands to the back
of the queue; the private <tt class="function">Run()</tt> function
removes commands from the front of the queue and executes them in
the internal thread. Figure 1 shows the structure of a 2-step Job
class.</p>
<p>The <tt class="classname">queue</tt> class simplifies the Job
functions by providing blocking read and write functions that are
unconditionally safe in a multi-threading environment. The
<span class="emphasis"><em>Command</em></span> objects call one of
the Job's member functions to do the real work.</p>
<p>A client at a higher level creates a Job and calls the
<tt class="function">Start()</tt> function, which creates a new
<tt class="classname">start-step-1</tt> command and adds it to the
queue. The <tt class="function">Run()</tt> function removes the
command from the front of the queue, executes it, which initiates
step1, and deletes it.</p>
<p>When step 1 finishes, a client at a lower level calls <tt class=
"function">Step1_Completed()</tt>, which adds a new <tt class=
"classname">start-step-2</tt> command to the back of the command
queue. The <tt class="function">Run()</tt> function removes the
command from the front of the queue, executes it, which initiates
step 2, and deletes it.</p>
<p>Similarly, when step 2 finishes, a client at a lower level calls
<tt class="function">Step2_Completed()</tt>, which adds a new
<tt class="classname">terminate</tt> command to the back of the
command queue. The <tt class="function">Run()</tt> function removes
the command from the front of the queue, executes it, which sets
the <tt class="varname">done</tt> flag, and deletes the command.
The <tt class="function">Run()</tt> function then exits its
processing loop and the thread terminates.</p>
<div class="sidebar">
<p class="title c2">Figure 2 - The Run() function.</p>
<pre class="programlisting">
virtual int Job::Run() {
  while (!done)
  {
    Command* command = queue.Get();
    (*command)();
    delete command;
  }
  return 0;
}
</pre></div>
<p>Note that all the public member functions execute in a client
thread and all the private member functions execute in the Job's
own thread. This is how the Job class hides its thread from the
client code.</p>
<p>Now, I could not help noticing that there is a lot of
duplication here. Top, Middle and Bottom Jobs all look much the
same. And the same pattern (small 'P') crops up elsewhere in our
code. This is a golden opportunity for some refactoring [<a href=
"#Fowler">Fowler</a>].</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e126" id=
"d0e126"></a>Refactoring</h2>
</div>
<p>In C++ there are several ways to factor out common code. We
could create a common base class, for example, or a class template
or a separate module all together. Which should we choose for the
family of Job classes?</p>
<p>The template option is not appropriate here because the Job
classes do not have a common interface. In the real application
Top, Middle and Bottom Jobs have public member functions with very
different names and purposes. A Job base class would cure the code
duplication problem for the Job classes, but the same problem
occurs elsewhere in the program. So, I think we are led to a more
general refactoring - one that works for active objects of all
kinds.</p>
<p>In the good old days, when multi-threading operating systems
were not generally available<sup>[<a name="d0e135" href=
"#ftn.d0e135" id="d0e135">1</a>]</sup>, many software systems were
divided into multiple processes. Such systems were often designed
using Mascot diagrams. Those diagrams showed processes as circles
and the processes were linked by &quot;channels&quot; that functioned as
message queues. In a Mascot diagram, &quot;process&quot; meant a real
(physical) process as known to the operating system. (Data flow
diagrams from the era of structured design methodologies are very
similar except that they show abstract (logical) processes. The
logical processes in a DFD could be nested and mapped to physical
processes in arbitrary ways.)</p>
<p>Designing systems using Mascot diagrams was relatively
straightforward. Concurrency problems did arise, but (as far as I
remember) they were less numerous and less troublesome than they
are in modern multi-threading programs. I think this is partly
because software these days is more complex and threads encourage
more concurrent processing. But it is also partly because the art
of designing software for a multi-threading environment seems to
have been lost.</p>
<p>The Mascot model is very general. It qualifies as a <span class=
"emphasis"><em>Design Pattern</em></span> (capital 'P') [<a href=
"#GoF">GoF</a>] and it solves certain problems of communication
between concurrent threads. So, instead of re-inventing the wheel,
I propose to use this Pattern to build a new thread model - an
&quot;application-oriented&quot; model - and then use the new thread model to
refactor the Top, Middle and Bottom Job classes.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e149" id=
"d0e149"></a>Application-Oriented Thread Model</h3>
</div>
<p>To keep things simple I shall describe a rather na&iuml;ve
implementation of the application-oriented thread model. Better
implementations will be mentioned, but not explained in detail.</p>
<p>The key feature of the application-oriented thread model is that
the thread class contains an input queue. The queue contains
pointers to function objects that are executed in sequence in the
context of the thread. Each function object must conform to the
interface defined by the <tt class="classname">thread::command</tt>
class.</p>
<div class="sidebar">
<p class="title c2">Figure 3 - Application-Oriented Thread
Interface.</p>
<pre class="programlisting">
// Generic thread class.
class thread {
public:
  class command;
  thread();
  ~thread();

  void push_back (command*);
  void terminate();
  void wait() const;
  . . .
private:
  class body;
  body* hidden_implementation;
};

class thread::command {
public:
  virtual ~command() {}
  virtual void operator() () = 0;
};
</pre></div>
<p>Figure 3 shows the thread and thread command classes. It also
shows a thread body class declared as an incomplete type. The
thread body hides all details of the implementation. (This is the
Cheshire Cat/Pimpl/Bridge Pattern, again.)</p>
<p>Once started, a Job proceeds in a series of event-driven steps.
The hardware drives the Bottom Jobs, which drive the Middle Jobs
which, in turn, drive the Top Jobs.</p>
<p>Like the Job classes illustrated above, client code adds
function objects to the queue using the <tt class=
"function">push_back()</tt> function while the hidden
implementation removes each function object from the queue,
executes it and disposes of it using the <tt class=
"literal">delete</tt> operator. A better implementation would
provide command objects in the form of Handles which could be
passed by value. This would provide a more flexible method of
managing the lifetime of the command objects.</p>
<p>The <tt class="function">terminate()</tt> function just adds a
'terminate' command object to the back of the queue. The
'terminate' command is provided by the implementation; it does not
have to be provided by the client code. Executing the 'terminate'
command causes the thread to terminate.</p>
<p>The <tt class="function">wait()</tt> function suspends the
calling thread until its own thread has terminated. When the
<tt class="function">wait()</tt> function returns it is safe to
destroy the thread object. A Handle/Body mechanism would provide
more flexible lifetime management here, too. (The previous article
in this series illustrates this technique.)</p>
<p>All the declarations should be in a suitable <tt class=
"literal">namespace</tt> to minimise the risk of name clashes.</p>
<p>The effect of refactoring the Job classes to use the new thread
model is illustrated in Figure 4.</p>
<div class="sidebar">
<p class="title c2">Figure 4 - The Refactored Job Class.</p>
<pre class="programlisting">
// 2-step Job class.
class Job : public thread {
public:
  void Start();

  void Step1_Completed();
  void Step2_Completed();
private:
  class Command;
  void Start_Step1();
  void Start_Step2();
};

void Job::Start() {
  push_back(new Command(this,&amp; Job::Start_Step1));
}
void Job::Step1_Completed() {
  push_back(new Command(this,
          &amp; Job::Start_Step2));
}

void Job::Step2_Completed(){
  terminate();
}
</pre></div>
<p>This version of a Job class inherits all the thread behaviour
from the thread class. It needs no user-defined constructor or
destructor, no implementation of the <tt class=
"function">Run()</tt> function, no <tt class=
"function">Terminate()</tt> function and none of the data that the
earlier version of the class required. The code that is left is all
specific to the Job class. And the interface has remained
unchanged. All the hallmarks of a successful refactoring are
here.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e209" id=
"d0e209"></a>Reflection</h2>
</div>
<p>We started with a family of active objects (the Top, Middle and
Bottom Jobs). We identified a classic case of unwarranted code
duplication. And we refactored to remove the duplication. The whole
process was a routine application of good programming principles
that led to a thread model that suited one particular program. But
we have not compared the new thread model with the more common
designs, nor have we considered whether the new model would be
useful in other applications.</p>
<p>In discussing these points, I must stress that I do not have
enough data for any firm conclusions. Nevertheless, it is worth
explaining how the application-oriented thread model arose and
exploring some of the characteristics of the two threading
models.</p>
<p>In our project, the Top, Middle, Bottom hierarchy of Jobs was
established early in the design. The normal path through each Job
is a simple sequence or repeating loop. However, the user can
intervene at any time to pause or abort the Job. At each step the
Job would initiate an asynchronous operation (e.g. start a
lower-level job or perform an operation on a device) and wait for
one of several outcomes (success, failure, pause or abort). The
Win32 <tt class="function">WaitForMultipleEvents()</tt> API call
seemed to provide a natural way to do this. In practice, though,
managing the multiple Event objects required by this approach
became rather complex.</p>
<p>Although it was far from clear at the time, replacing the
multiple Events with some sort of message queue simplified the
design considerably. A Job could now wait for a &quot;new message&quot;
event, read the message and perform some appropriate action. In
effect, multiple un-parameterised Events were replaced by a single
parameterised Event, with the message as the parameter.</p>
<p>The down side of a classic message queue is that the receiving
function tends to become a big, error-prone <tt class=
"literal">switch</tt> statement. Our answer to that problem was to
put Command objects into the input queue. Or rather, pointers to
Command objects because Commands are necessarily polymorphic. And
that is the design described at the beginning of this article.</p>
<p>This is just one team's experience and one data point does not
make a trend, but it suggests that threads and input queues work
well together. The design methods based on Mascot and Data Flow
diagrams seem to support this idea. The input queue of the
application-oriented model does, of course, carry more overhead
than the lower-level thread designs supported by most threading
libraries. But I wonder if multi-threaded applications usually
build in such machinery anyway. If so, a library supporting
application-oriented threading could be a useful addition to the
programmer's toolkit.</p>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e230" id="d0e230"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Fowler" id="Fowler"></a>
<p class="bibliomixed">[Fowler] <span class="citetitle"><i class=
"citetitle">Refactoring - Improving the Design of Existing
Code</i></span>, by Martin Fowler, ISBN 0-201-48567-2.</p>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] <span class="citetitle"><i class=
"citetitle">Design Patterns - Elements of Reusable Object-Oriented
Software</i></span>, by Erich Gamma, Richard Helm, Ralph Johnson
and John Vlissides, ISBN 0-201-63361-2.</p>
</div>
</div>
</div>
<div class="footnotes"><br>
<hr class="c3" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e135" href="#d0e135" id=
"ftn.d0e135">1</a>]</sup> In those days operating systems were
simple, efficient and reliable.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
