    <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  :: Patterns in C - Part 5: REACTOR</title>
        <link>https://members.accu.org/index.php/articles/835</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">Design of applications and programs + CVu Journal Vol 17, #5 - Oct 2005</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/c67/">Design</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/c77/">CVu</a>

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

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

                    -                        <a href="https://members.accu.org/index.php/articles/c67+94/">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;Patterns in C - Part 5: REACTOR</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 October 2005 06:00:00 +01:00 or Sun, 02 October 2005 06:00:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;<p>This final part of the series will step outside the domain of standard C and investigate a pattern for event-driven applications. The REACTOR pattern decouples different responsibilities and allows applications to demultiplex and dispatch events from potentially many clients.</p></p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>This final part of the series will step outside the domain of
standard C and investigate a pattern for event-driven applications.
The REACTOR pattern decouples different responsibilities and allows
applications to demultiplex and dispatch events from potentially
many clients.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e24" id="d0e24"></a>The Case of
Many Clients</h2>
</div>
<p>In order to simplify maintenance of large systems, the
diagnostics of the individual subsystems are gathered in one,
central unit. Each subsystem connects to the diagnostics server
using TCP/IP. As TCP/IP is a connection-oriented protocol, the
clients (the different subsystems) have to request a connection at
the server. Once a connection is established, a client may send
diagnostics messages at any time.</p>
<p>The brute-force approach is to scan for connection requests and
diagnostics messages from the clients one by one as illustrated in
the activity diagram in Figure 1.</p>
<div class="figure"><a name="d0e31" id="d0e31"></a>
<div class="mediaobject c3"><img src=
"resources/Patterns%20in%20C(1).png" align="middle" alt=
"Eternal loop to scan for different events"></div>
<p class="title c4">Figure 1. Eternal loop to scan for different
events</p>
</div>
<p>Even in this strongly simplified example, there are several
potential problems. By intertwining the application logic with the
networking code and the code for event dispatching, several
unrelated responsibilities have been built into one module. Such a
design is likely to lead to serious maintenance, testability, and
scalability problems by violating a fundamental design
principle.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e39" id="d0e39"></a>The Single
Responsibility Principle</h2>
</div>
<p>The single responsibility principle states that &quot;a class should
have only one reason to change&quot; [<a href="#Martin">Martin</a>]. The
goal of this principle is close to that of the open-closed
principle treated below: both strive to protect existing code from
modifications. When violating the single responsibility principle,
a module gets more reasons to change and modifications to it become
more likely. Worse, the different responsibilities absorbed by a
single module may become coupled and interact with each other
making modifications and testing of the module more
complicated.</p>
<p>The single responsibility principle is basically about cohesion.
It is useful and valuable on many levels of abstraction, not at
least in a procedural context; simply replacing the word &quot;class&quot;
with &quot;function&quot; enables us to analyze algorithms like the one above
with respect to this principle.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e49" id="d0e49"></a>Violation of
the Open-Closed Principle</h2>
</div>
<p>By violating the single responsibility principle, the module in
the example above will be hard to maintain; it is code that one
never wants to dig into in the future. Unfortunately, on collision
course with that wish is the fact that the event loop above
violates the open-closed principle [<a href="#Martin">Martin</a>];
new functionality cannot be added without modifying existing code.
Related to our example, a diagnostics server typically allows a
technician to connect and query stored information. Introducing
that functionality would double the logic in the event loop.
Clearly, this design makes the code expensive to modify.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e57" id="d0e57"></a>From a
Performance Perspective</h2>
</div>
<p>To make things worse, the solution above fails to scale in terms
of performance as well. As all events are scanned serially, even in
case timeouts are used, valuable time is wasted doing nothing.</p>
<p>The potential performance problem above may be derived from the
failure of taking the concurrent nature of the problem into
account. One approach to address this problem is by introducing
multiple threads. The diagnostics server keeps its event loop, but
the loop is now reduced to scan for connection requests. As soon as
a connection is requested, a new thread is allocated exclusively
for handling messages on that new connection.</p>
<p>The multithreading approach fails to address the overall design
issue as it still violates both the single responsibility principle
and the open-closed principle. Although the code for scanning and
dispatching diagnostics messages is moved out of the event loop,
adding a new server-port still requires modifications to existing
code.</p>
<p>From a design perspective threads didn't improve anything. In
fact, even with respect to performance, this solution may due to
context switches and synchronization actually perform worse than
the initial single-threaded approach.</p>
<p>The sheer complexity inherent in designing and implementing
multithreaded applications is a further argument for discarding
this solution.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e70" id="d0e70"></a>Problem
Summary</h2>
</div>
<p>Summarizing the experience so far, the design fails as it
assumes three different responsibilities. This problem is bound to
be worse as the design violates the open-closed principle, making
modifications to existing code more likely.</p>
<p>Summarizing the ideal solution, it should scale well,
encapsulate and decouple the different responsibilities, and be
able to serve multiple clients simultaneously without introducing
the liabilities of multithreading. The REACTOR pattern realizes
this solution by encapsulating each service of the application
logic in event handlers and separating out the code for event
demultiplexing.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e77" id="d0e77"></a>The REACTOR
Pattern</h2>
</div>
<p>The intent of the REACTOR pattern is: &quot;<span class="quote">The
REACTOR architectural pattern allows event-driven applications to
demultiplex and dispatch service requests that are delivered to an
application from one or more clients [<a href=
"#POSA">POSA</a>].</span>&quot;</p>
<div class="figure"><a name="d0e87" id="d0e87"></a>
<div class="mediaobject c3"><img src=
"resources/Patterns%20in%20C(2).png" align="middle" alt=
"Structure of the REACTOR Pattern"></div>
<p class="title c4">Figure 2. Structure of the REACTOR Pattern</p>
</div>
<p>The roles of the involved participants are:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><tt class="classname">EventHandler</tt>: An <tt class=
"classname">EventHandler</tt> defines an interface to be
implemented by modules reacting to events. Each <tt class=
"classname">EventHandler</tt> own its own <tt class=
"classname">Handle</tt>.</p>
</li>
<li>
<p><tt class="classname">Handle</tt>: An efficient implementation
of the REACTOR pattern requires an OS that supports handles
(examples of <tt class="classname">Handle</tt>s include system
resources like files, sockets, and timers).</p>
</li>
<li>
<p><tt class="classname">DiagnosticsServer</tt> and <tt class=
"classname">DiagnosticsClient</tt>: These two are concrete event
handlers, each one encapsulating one responsibility. In order to be
able to receive event notifications, the concrete event handlers
have to register themselves at the <tt class=
"classname">Reactor</tt>.</p>
</li>
<li>
<p><tt class="classname">Reactor</tt>: The <tt class=
"classname">Reactor</tt> maintains registrations of <tt class=
"classname">EventHandler</tt>s and fetches the associated
<tt class="classname">Handle</tt>s. The <tt class=
"classname">Reactor</tt> waits for events on its set of registered
<tt class="classname">Handle</tt>s and invokes the corresponding
<tt class="classname">EventHandler</tt> as a <tt class=
"classname">Handle</tt> indicates an event.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e155" id="d0e155"></a>Event
Detection</h2>
</div>
<p>In its description of REACTOR, <i class=
"citetitle">Pattern-Oriented Software Architecture</i> [<a href=
"#POSA">POSA</a>] defines a further collaborator, the <tt class=
"classname">Synchronous Event Demultiplexer</tt>. The <tt class=
"classname">Synchronous Event Demultiplexer</tt> is called by the
<tt class="classname">Reactor</tt> in order to wait for events to
occur on the registered <tt class="classname">Handle</tt>s.</p>
<p>A synchronous event demultiplexer is often provided by the
operating system. This example will use <tt class=
"function">poll()</tt> (<tt class="function">select()</tt> and
Win32's <tt class="function">WaitForMultipleObjects()</tt> are
other functions available on common operating systems), which works
with any descriptor.</p>
<p>The code interacting with <tt class="function">poll()</tt> will
only be provided as a sketch, because the POSIX specific details
are outside the scope of this article. The complete sample code,
used in this article, is available from my homepage [<a href=
"#source">source</a>].</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e197" id=
"d0e197"></a>Implementation Mechanism</h2>
</div>
<p>The collaboration between an <tt class=
"classname">EventHandler</tt> and the <tt class=
"classname">Reactor</tt> is similar to the interaction between an
observer and its subject in the design pattern OBSERVER [<a href=
"#GoF">GoF</a>]. This relationship between these two patterns
indicates that the techniques used to realize OBSERVER in C
[<a href="#Petersen2">Petersen2</a>] may serve equally well to
implement the REACTOR.</p>
<p>In order to decouple the <tt class="classname">Reactor</tt> from
its event handlers and still enable the <tt class=
"classname">Reactor</tt> to notify them, each concrete event
handler must correspond to a unique instance. In our OBSERVER
implementation, the FIRST-CLASS ADT pattern [<a href=
"#Petersen1">Petersen1</a>] was put to work to solve this problem.
As all concrete event handlers have to be abstracted as one,
general type realizing the <tt class="classname">EventHandler</tt>
interface, <tt class="type">void*</tt> is chosen as &quot;the general
type&quot; to be registered at the <tt class="classname">Reactor</tt>
(please refer to the previous part in this series - Reference
[<a href="#Petersen2">Petersen2</a>] - for the rationale and
technical reasons behind the <tt class="type">void*</tt>
abstraction). These decisions enable a common interface for all
event handlers:</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e240" id="d0e240"></a>Listing 1 :
Interface of the event handlers, EventHandler.h</h3>
</div>
<pre class="programlisting">
/* The type of a handle is system specific - this example uses UNIX I/O handles, which are plain integer values. */
typedef int Handle;

/* All interaction from Reactor to an event handler goes through function pointers with the following signatures: */
typedef Handle (*getHandleFunc)
   (void* instance);
typedef void (*handleEventFunc)
   (void* instance);

typedef struct
{
  void* instance;
  getHandleFunc getHandle;
  handleEventFunc handleEvent;
} EventHandler;
</pre>
<p>Having this interface in place allows us to declare the
registration functions of the <tt class=
"classname">Reactor</tt>.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e250" id="d0e250"></a>Listing 2 :
Registration interface of the Reactor, Reactor.h</h3>
</div>
<pre class="programlisting">
#include &quot;EventHandler.h&quot;

void Register(EventHandler* handler);
void Unregister(EventHandler* handler);
</pre>
<p>The application specific services have to implement the
<tt class="classname">EventHandler</tt> interface and register
themselves using the interface above in order to be able to react
to events.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e260" id="d0e260"></a>Listing 3 :
Implementation of a concrete event handler,
DiagnosticsServer.c</h3>
</div>
<pre class="programlisting">
#include &quot;EventHandler.h&quot;

struct DiagnosticsServer
{
   Handle listeningSocket;
   EventHandler eventHandler;
  
   /* Other attributes here... */
};
/* Implementation of the EventHandler interface. */
static Handle getServerSocket(void* instance)
{
  const DiagnosticsServerPtr server = 
     instance;
  return server-&gt;listeningSocket;
}

static void handleConnectRequest(void* instance)
{
  DiagnosticsServerPtr server = instance;
  
  /* The server gets notified as a new connection request arrives. 
     Add code for accepting the new connection and creating a client here... */
}

DiagnosticsServerPtr createServer
   (unsigned int tcpPort)
{
  DiagnosticsServerPtr newServer = 
     malloc(sizeof *newServer);

  if(NULL != newServer) {
  /* Code for creating the server socket here.
     The real code should look for a failure,
     etc. */
      newServer-&gt;listeningSocket = 
         createServerSocket(tcpPort);

      /* Successfully created -&gt; register the
         listening socket. */
       newServer-&gt;eventHandler.instance = 
          newServer;
       newServer-&gt;eventHandler.getHandle =
          getServerSocket;
       newServer-&gt;eventHandler.handleEvent =
          handleConnectRequest;

      Register(&amp;newServer-&gt;eventHandler);
   }
   return newServer;
}

void destroyServer
   (DiagnosticsServerPtr server)
{
   /* Before deleting the server we have to
      unregister at the Reactor. */
   Unregister(&amp;server-&gt;eventHandler);

   free(server);
}
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e265" id="d0e265"></a>REACTOR
Registration Strategy</h2>
</div>
<p>When implementing the concrete event handlers as a FIRST-CLASS
ADT, the functions for creating and destructing the ADT serves well
to encapsulate the registration handling. The advantage is the
combination of loose dependencies with information hiding as a
client does not even have to know about the usage and interactions
with the <tt class="classname">Reactor</tt>.</p>
<p>Another attractive property is that the internals of the server,
in our example the handle, is encapsulated within the <tt class=
"function">getServerSocket</tt> function. Sure, we are giving the
<tt class="classname">Reactor</tt> a way to fetch it, but the
<tt class="classname">Reactor</tt> is considered a well-trusted
collaborator and we are actively giving it access by registering
our event handler. There is no way for any other module to
mistakenly fetch the handle and corrupt the associated
resource.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e284" id="d0e284"></a>REACTOR
Implementation</h2>
</div>
<p>The details of the REACTOR implementation are platform specific
as they depend upon the available synchronous event demultiplexers.
In case the operating system provides more than one synchronous
event demultiplexer (e.g. <tt class="function">select()</tt> and
<tt class="function">poll()</tt>), a concrete <tt class=
"classname">Reactor</tt> may be implemented for each one of them
and the linker used to chose either one of them depending on the
problem at hand. This technique is referred to as link-time
polymorphism.</p>
<p>Each <tt class="classname">Reactor</tt> implementation has to
decide upon the number of reactors required by the surrounding
application. In the most common case, the application can be
structured around one, single <tt class="classname">Reactor</tt>.
In this case, the interface in Listing 2 (<tt class=
"filename">Reactor.h</tt>) will serve well. An application
requiring more than one <tt class="classname">Reactor</tt> should
consider making the <tt class="classname">Reactor</tt> itself a
FIRST-CLASS ADT. This second variation complicates the clients
slightly as references to the <tt class="classname">Reactor</tt>
ADT have to be maintained and passed around in the system.</p>
<p>Independent of the system specific demultiplexing mechanism, a
<tt class="classname">Reactor</tt> has to maintain a collection of
registered, concrete event handlers. In its simplest form, this
collection may simply be an array. This approach serves well in
case the maximum number of clients is known in advance.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e323" id="d0e323"></a>Listing 4:
Implementation of a Reactor using poll(), PollReactor.c</h3>
</div>
<pre class="programlisting">
#include &quot;Reactor.h&quot;
#include &lt;poll.h&gt;
/* Other include files omitted... */

/* Bind an event handler to the struct used to
   interface poll(). */
typedef struct
{
   EventHandler handler;
   struct pollfd fd;
} HandlerRegistration;

static HandlerRegistration registeredHandlers[MAX_NO_OF_HANDLES];

/* Add a copy of the given handler to the first free position in registeredHandlers. */
static void addToRegistry(EventHandler* handler);
  /* Identify the event handler in the registeredHandlers and remove it. */
static void removeFromRegistry(EventHandler* 
   handler);

/* Implementation of the Reactor interface used for registrations.*/
void Register(EventHandler* handler)
{
   assert(NULL != handler);
   addToRegistry(handler);
}

void Unregister(EventHandler* handler)
{
   assert(NULL != handler);
   removeFromRegistry(handler);
}
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e328" id="d0e328"></a>Invoking the
Reactor</h2>
</div>
<p>The reactive event loop is the core of the <tt class=
"classname">Reactor</tt> and its responsibilities are to control
the demultiplexing and dispatch the detected events to the
registered, concrete event handlers. The event loop is contained
within the <tt class="function">HandleEvents()</tt> function and is
typically invoked from the <tt class="function">main()</tt>
function.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e342" id="d0e342"></a>Listing 5:
Client code driving the reactor</h3>
</div>
<pre class="programlisting">
int main(void){
   const unsigned int serverPort = 0xC001;
   DiagnosticsServerPtr server = 
      createServer(serverPort);
   if(NULL == server) {
      error(&quot;Failed to create the server&quot;);
   }
   /* Enter the eternal reactive event loop.*/
   for(;;){
      HandleEvents();
   }
}
</pre>
<p>Before investigating the implementation, which include file
should provide the declaration of the <tt class=
"function">HandleEvents()</tt> function? Unfortunately, adding it
to the file in Listing 2 (<tt class="filename">Reactor.h</tt>)
would clearly make that interface less cohesive; the registration
functions models a different responsibility than the event loop. A
solution is to create a separate interface for the event loop. This
interface is intended solely for the compilation unit invoking the
event loop.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e355" id="d0e355"></a>Listing 6:
Interface to the event loop, ReactorEventLoop.h</h3>
</div>
<pre class="programlisting">
void HandleEvents(void);
</pre>
<p>Despite its simplicity, this separation solves the cohesiveness
problem and shields clients from functions they do not use. This
technique of providing separate interfaces to separate clients is
known as the interface-segregation principle [<a href=
"#Martin">Martin</a>].</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e365" id="d0e365"></a>Implementing
the Event Loop</h2>
</div>
<p>With the interface in place, we can move on and implement the
event loop itself. The listing below extends Listing 4.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e370" id="d0e370"></a>Listing 7:
Example of a reactive event loop, PollReactor.c</h3>
</div>
<pre class="programlisting">
#include &quot;ReactorEventLoop.h&quot;
/* The code from Listing 4 go here (omitted)... */

/* Add a copy of all registered handlers to the given array. */
static size_t buildPollArray
   (struct pollfd* fds);

  /* Identify the event handler corresponding to the given 
     descriptor in the registeredHandlers. */
static EventHandler* findHandler(int fd);

static void dispatchSignalledHandles(
      const struct pollfd* fds,
      size_t noOfHandles)
{
   /* Loop through all handles. Upon detection of a handle signalled by poll, 
      its corresponding event handler is fetched and invoked. */
   size_t i = 0;
   for(i = 0; i &lt; noOfHandles; ++i) {
      /* Detect all signalled handles and invoke their corresponding 
         event handlers. */
      if((POLLRDNORM | POLLERR) &amp; 
         fds[i].revents) {
         EventHandler* signalledHandler =
         findHandler(fds[i].fd);

         if(NULL != signalledHandler){
            signalledHandler-&gt; handleEvent
            (signalledHandler-&gt;instance);
         }
      }
   }
}
/*Implementation of the reactive event loop.*/
void HandleEvents(void)
{
   /* Build the array required to interact with poll().*/
   struct pollfd fds[MAX_NO_OF_HANDLES] = {0};
   const size_t noOfHandles = 
      buildPollArray(fds);
/*Invoke the synchronous event demultiplexer*/
   if(0 &lt; poll(fds, noOfHandles, INFTIM)){
   /* Identify all signalled handles and
   invoke the event handler associated with 
   each one. */
      dispatchSignalledHandles(fds,
          noOfHandles);
   }
   else{
      error(&quot;Poll failure&quot;);
   }
}
</pre>
<p>The example above lets each element in the collection maintain a
binding between the registered event handler and the structure used
to interact with <tt class="function">poll()</tt>. One alternative
approach is to keep two separate lists and ensure consistency
between them. <i class="citetitle">Pattern-Oriented Software
Architecture</i> [<a href="#POSA">POSA</a>] describes another,
system specific alternative: in a UNIX implementation using
<tt class="function">select()</tt>, the &quot;<span class="quote">array
is indexed by UNIX I/O handle values, which are unsigned integers
ranging from 0 to FD_SETSIZE-1</span>&quot;.</p>
<p>Returning to the example, by grouping the registration and the
poll-structure together, the array used to interact with <tt class=
"function">poll()</tt> has to be built each time the reactive event
loop is entered. In case the performance penalty is acceptable,
this is probably a better choice as it enables a simpler handling
of registrations and unregistrations during the event loop.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e397" id="d0e397"></a>Handling New
Registrations</h2>
</div>
<p>In my previous article [<a href="#Petersen2">Petersen2</a>], I
discussed strategies for managing changed registrations during the
notification of observers. The alternative of forbidding changed
registrations is, unlike the OBSERVER pattern, not an option for a
REACTOR implementation. In the example used in this article, the
server reacts to the notification by creating a new client, which
must be registered shall it ever be activated again. This leaves
only one option for a REACTOR implementer: ensure that it
works.</p>
<p>One solution is to maintain a separate array to interact with
the synchronous event demultiplexer as illustrated above. This
array is never modified in the event loop. However, this solution
has the consequence that handles unregistered during the current
event loop may be marked as signalled in the separate array. The
code simply has to check for this case and ignore such handles, as
illustrated by the function <tt class=
"function">dispatchSignalledHandles</tt> in Listing 7 above.</p>
<p>The code uses the handle alone as identification. In cases
resources are disposed and created during the same event loop,
there is, depending on platform, a possibility that the handle ID's
are re-used; a signalled handle in the copy may belong to an
unregistered event handler, but due to a new registration using the
re-cycled handle ID, the new event handler may be erroneously
invoked. If this is an issue, the problem may be prevented by
introducing further book-keeping data. For example, a second array
containing the identities of the handles unregistered during the
current event loop makes it possible to identify the case described
above and thus avoid it.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e412" id="d0e412"></a>More Than One
Type of Event</h2>
</div>
<p>The design in the example above does only allow applications to
register for one type of event (read-events). The event type is
even hardcoded in the Reactor and it is a simple solution
sufficient for applications without any need for further event
detection. The REACTOR pattern, however, is not limited to one type
of event. The pattern scales well to support different types of
events.</p>
<p><i class="citetitle">Pattern-Oriented Software Architecture</i>
[<a href="#POSA">POSA</a>] describes two general strategies for
dispatching event notifications:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Single-method interface: An event handler is notified about all
events through one, single function. The type of event (typically
in the form of an <tt class="literal">enum</tt>) is passed as a
parameter to the function. The disadvantage of this approach is
that it sets the stage for conditional logic, which soon gets hard
to maintain.</p>
</li>
<li>
<p>Multi-method interface: In this case, the event handler declares
separate functions for each supported event (e.g. <tt class=
"function">handleRead</tt>, <tt class="function">handleWrite</tt>,
<tt class="function">handleTimeout</tt>). As the <tt class=
"classname">Reactor</tt> has the knowledge of what event occurred,
it invokes the corresponding function immediately, thus avoiding
placing the burden on the event handler to re-create the event from
a parameter.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e446" id="d0e446"></a>Comparision
of REACTOR and OBSERVER</h2>
</div>
<p>Although the mechanisms used to implement them are related,
there are differences between these two patterns. The main
difference is in the notification mechanism. As a <tt class=
"classname">Subject</tt> changes its state in an OBSERVER
implementation, all its dependents (observers) are notified. In a
REACTOR implementation, this relationship is one to one - a
detected event leads the <tt class="classname">Reactor</tt> to
notify exactly one dependent (<tt class=
"classname">EventHandler</tt>).</p>
<p>One typical liability of the OBSERVER pattern is that the
cohesion of the subject is lowered; besides serving its central
purpose, a subject also takes on the responsibility of managing and
notifying observers. With this respect, a <tt class=
"classname">Reactor</tt> differs significantly as its whole raison
d'&ecirc;tre is to dispatch events to its registered handlers.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e465" id=
"d0e465"></a>Consequences</h2>
</div>
<p>The main consequences of applying the REACTOR pattern are:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><span class="emphasis"><em>The benefits of the
single-responsibility principle</em></span>. Using the REACTOR
pattern, each of the responsibilities above is encapsulated and
decoupled from each other. The design results in increased
cohesion, which simplifies maintenance and minimizes the risk of
feature interaction.</p>
<p>As the platform dependent code for event detection is decoupled
from the application logic, unit testing is greatly simplified (it
is straightforward to simulate events through the <tt class=
"classname">EventHandler</tt> interface).</p>
</li>
<li>
<p><span class="emphasis"><em>The benefits of the open-closed
principle</em></span>. The design now adheres to the open-closed
principle. New responsibilities, in the form of new event handlers,
may be added without affecting the existing event handlers.</p>
</li>
<li>
<p><span class="emphasis"><em>Unified mechanism for event
handling</em></span>. Even if the REACTOR pattern is centred on
handles, it may be extended for other tasks. <i class=
"citetitle">Pattern-Oriented Software Architecture</i> [<a href=
"#POSA">POSA</a>] describes different strategies for integrating
the demultiplexing of I/O events with timer handling. Extending the
<tt class="classname">Reactor</tt> with timer support is an
attractive alternative to typical platform specific solutions based
upon signals or threads. This extension builds upon the possibility
to specify a timeout value when invoking the synchronous event
demultiplexer (for example, <tt class="function">poll()</tt> allows
a timeout to be specified with a resolution of milliseconds).
Although it will possibly not suit a hard real-time system, a
<tt class="classname">Reactor</tt> based timer mechanism is easier
to implement and use than a signal or thread based solution as it
tends to avoid re-entrance problems and race-conditions.</p>
</li>
<li>
<p><span class="emphasis"><em>Provides an alternative to
multithreading</em></span>. Using the REACTOR pattern, blocking
operations in the concrete event handlers can typically be avoided
and consequently also multithreading. As discussed above, a
multithreaded solution does not only add significant complexity; it
may also prove to be less efficient in terms of run-time
performance. However, as the <tt class="classname">Reactor</tt>
implies a non pre-emptive multitasking model, each concrete event
handler must ensure that it does not perform operations that may
starve out other event handlers.</p>
</li>
<li>
<p><span class="emphasis"><em>Trades type-safety for
flexibility</em></span>. All concrete event handlers are abstracted
as <tt class="type">void*</tt>. When converting a void-pointer back
to a pointer of a concrete event handler type, the compiler doesn't
have any way to detect an erroneous conversion This potential
problem was faced in the implementation of the OBSERVER pattern
[<a href="#Petersen2">Petersen2</a>] and the solution is the same
for the REACTOR: define unique notification functions for each
different type of event handler and bind the functions and event
handler together using an <tt class="classname">EventHandler</tt>
structure as described in Listing 1.</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e528" id="d0e528"></a>Summary</h2>
</div>
<p>The REACTOR pattern simplifies event-driven applications by
decoupling the different responsibilities, encapsulated in separate
modules.</p>
<p>There is much more to the REACTOR pattern than described in this
article. Particularly several variations that all come with
different benefits and trade-offs. For an excellent in-depth
treatment of the REACTOR and other patterns in the domain, I
recommend the book <i class="citetitle">Pattern-Oriented Software
Architecture, volume 2</i> [<a href="#POSA">POSA</a>].</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e541" id=
"d0e541"></a>Acknowledgements</h2>
</div>
<p>Many thanks to Drago Krznaric and Andr&eacute; Saitzkoff for
their feedback.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e546" id="d0e546"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Martin" id="Martin"></a>
<p class="bibliomixed">[Martin] Robert C. Martin: &quot;<span class=
"citetitle"><i class="citetitle">Agile Software
Development</i></span>&quot;, Prentice Hall</p>
</div>
<div class="bibliomixed"><a name="POSA" id="POSA"></a>
<p class="bibliomixed">[POSA] Schmidt, Stal, Rohnert, Buschmann:
&quot;<span class="citetitle"><i class="citetitle">Pattern-Oriented
Software Architecture, volume 2</i></span>&quot;, Wiley</p>
</div>
<div class="bibliomixed"><a name="Petersen1" id="Petersen1"></a>
<p class="bibliomixed">[Petersen1] Adam Petersen, &quot;Patterns in C,
part 1&quot;, <span class="citetitle"><i class="citetitle">C
Vu</i></span> 17.1</p>
</div>
<div class="bibliomixed"><a name="Petersen2" id="Petersen2"></a>
<p class="bibliomixed">[Petersen2] Adam Petersen, &quot;Patterns in C,
part 4: OBSERVER&quot;, <span class="citetitle"><i class="citetitle">C
Vu</i></span> 17.4</p>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] Gamma, E., Helm, R., Johnson, R., and
Vlissides, J, &quot;<span class="citetitle"><i class="citetitle">Design
Patterns</i></span>&quot;, Addison-Wesley</p>
</div>
<div class="bibliomixed"><a name="source" id="source"></a>
<p class="bibliomixed">[source] The complete REACTOR sample code
used in this article, <span class="bibliomisc"><a href=
"http://www.adampetersen.se" target=
"_top">www.adampetersen.se</a></span></p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
