he code below is the public ThreadMaster interface.
Lines 4-5. For boost::function syntax see the documentation of the
boost::function library.
Line 7: NThreads is the number of the worker threads doing the parallel
processing of every stage.
Lines 8,9: Copy-by-value semantics.
Line 10: The add function allows to supply the operation performed on every
stage (first argument "job") and the termination condition (second argument
"condition"). Each worker thread calls Job::operator()(). After the control is
returned on every step, the Condition::operator()() will be called on a single
thread. If "false" is returned then the processing ends. The ThreadMaster
maintains the vector of Jobs and Conditions. Each stage is represented by an
entry in such vector. Stages are executed in the same order they were supplied
by "add". After completion of the last stage the ThreadMaster resumes from the
first stage (that is from index 0). The "add" will throw
AlreadyRunningException if the "run" was already called and, hence, the
processing is already started.
Line 11: The "run" starts the processing. After the call to "run" no calls to
"add" are allowed.
Line 12: Check if "run" was called.
Line 13: If Job throws then the ThreadMaster restarts that working thread. The
supplied here Job will be executed on the freshly restarted thread before that
stage's regular Job is executed.
The interface of the ThreadMaster is not thread-safe. The intended usage is
consecutive calls to the Constructor, several calls to the "add", one or none
calls to the "onRestart" and a single call to the "run". After the call to the
"run" the ThreadMaster becomes effectively immutable.
1\
class
ThreadMaster
2\
{
3\
public:
4\
typedef
boost::function0<void> Job;
5\
typedef
boost::function0<bool> Condition;
6\
public:
7\
explicit
ThreadMaster( int Nthreads );
8\
ThreadMaster(
const ThreadMaster& tm );
9\
ThreadMaster&
operator=( const ThreadMaster& tm );
10\
void
add( const Job& job, const Condition& terminalCondition );
11\
void
run();
12\
bool
isRunning() const;
13\
void
onRestart( const Job& onRestart );
14\
class
AlreadyRunningException : public std::exception, public boost::exception
{};
15\
};
|