...

/

Implementing the Reactor Pattern - Part 2

Implementing the Reactor Pattern - Part 2

In this lesson, we will continue with the implementation of the Reactor pattern in the C language.

Reactor Implementation

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. select() and poll()), we can implement a concrete Reactor for each of them as well as the linker used to determine the event. This technique is referred to as link-time polymorphism.

Press + to interact
#include "EventHandler.h"
void Register(EventHandler* handler);
void Unregister(EventHandler* handler);

Each Reactor implementation has to decide upon the number of reactors required by the surrounding application. In the most common case, we can structure the application around one single Reactor. In this case, the interface in Listing 2 (Reactor.h) will serve well. An application requiring more than one Reactor should consider making the Reactor itself a First-Class ADT. This second variation complicates the clients slightly as references to the Reactor ADT must be maintained and passed around in the system.

Independent of the system-specific demultiplexing mechanism, a Reactor has to maintain a collection of registered, concrete event handlers. In its simplest form, this collection will simply be an array. When we know the maximum number of clients in advance, this approach serves well.

Press + to interact
#include "Reactor.h"
#include <poll.h>
/* 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);
}

Invoking the Reactor

The reactive ...