"BOSS-WORKERS" APPLICATION MODEL WITH PTHREADS
The goal of small C++ framework presented here is to make development of multithreading server programs easier. Framework consists of several C++ modules:
| threading.cpp | TBaseThread class - thread wrapper with some predefined behaviour. |
| message.h | Base message classes - to communicate between threads. |
| synchronisation.cpp | Basic synchronisation primitives used in framework |
| commands.h | Basic messages used to control threads - common for all applications |
TBaseThread class
The base class - TBaseThread actually is pthreads thread with message queue and methods that let safely push and extract messages to/from queue. TBaseThread object behaviour is concentrated in thread function MainLoop. Thread function contains the message processing loop between Preambulae() and Poscriptum() calls. Preambulae and Postscriptum are virtual functions that give developer opportunity to make something before/after thread enters message processing loop. All pthreads specific stuff is hidden from user.
void Threading::TBaseThread::MainLoop()
{
Preambulae();
bool fdispose = false;
while(IsMainState())
{
Threading::TBaseMessage *msg = GetMessage();
if(msg)
{
fdispose = DisposeMessage(msg);
ProcessMessage(msg);
if(fdispose)
delete msg;
}
Yeld();
}
Postsriptum();
pthread_exit((void *)0);
}
The most important function within message processing loop is
ProcessMessage. This function is pure virtual and developer should implement it's own message processing mechanism. DisposeMessage is virtual and decides - delete received message or leave it.
Simple "boss-workers" application
Simple multithreading application illustrates use of multithreading framework. There are two thread classes: TDispatcher ("boss") and TWorker ("worker"). TDispatcher creates N TWorker objects and dispatches jobs between them. Application code contains example how to coordinate threads (create workers pool, distribute jobs between workers, correctly stop threads ensemble). You can use this sample as skeleton for real life application. I successfully used proposed multithreading schema developing complex server programs.