Listing 1: ThreadMediator.h
/*===========================================================*\
\*===========================================================*/
#if !defined(__THREAD_MEDIATOR_H__)
#define __THREAD_MEDIATOR_H__
namespace Tx
{
//=========================================================
// Abstract base class for polymorphic mediator handling
class ThreadMediator
{
public:
ThreadMediator() {}
virtual ~ThreadMediator() {}
// These are called by external controlling thread
virtual void Signal() = 0;
virtual void ResetSignal() = 0;
private:
// Disallow copy constructor/assignment operators
ThreadMediator(const ThreadMediator &);
ThreadMediator & operator=(const ThreadMediator &);
};
//=========================================================
// You instantiate this class with your own synchronizer
template <class Synchronizer>
class ThreadMediatorImpl : public ThreadMediator
{
public:
typedef Synchronizer Synchronizer_t;
typedef Synchronizer::SyncObject_t SyncObject_t;
typedef Synchronizer::TimeDuration_t TimeDuration_t;
typedef Synchronizer::Exception_t Exception_t;
typedef Synchronizer::Mutex_t Mutex_t;
ThreadMediatorImpl() : _signalFlag(false) {}
virtual ~ThreadMediatorImpl() {}
// These are called by external controlling thread
virtual void Signal()
{
_mutex.Lock();
_signalFlag = true;
_mutex.Unlock();
_synchronizer.Signal();
}
virtual void ResetSignal()
{
_mutex.Lock();
_signalFlag = false;
_mutex.Unlock();
_synchronizer.Reset();
}
// These are called by the child threads
bool Wait( const SyncObject_t & syncObject,
TimeDuration_t timeout) const
{
return _synchronizer.Wait(
syncObject,
timeout);
}
void Sleep(TimeDuration_t timeout) const
{
_synchronizer.Sleep(timeout);
}
void Poll() const
{
_mutex.Lock();
bool bSignalled = _signalFlag;
_mutex.Unlock();
if (bSignalled)
throw Synchronizer::Exception_t();
}
private:
Synchronizer_t _synchronizer;
mutable Mutex_t _mutex;
bool _signalFlag;
};
}
#endif // __THREAD_MEDIATOR_H__