boost::thread
I am trying to make a thread object, so I can later have better
control of threads and the resources they are using. So, I started
wrapping up a boost::thread.
//---------------------------------------------------------------------------------------------------------------------------------------------
// BaseThread.h
#include <boost/thread/thread.hpp>
//------------------------------------------------------------------------------
/// \brief Thread object that performs a task that is to run once (non-
looped)
/// \detail Derive from this class and implement the Work method to
define the
/// work this thread is to perform
class BaseThread
{
public:
BaseThread();
/// \brief Deconstructor
/// \detail It is required that a derived class make a call to
thread_.join()
/// in its deconstructor
virtual ~BaseThread();
virtual void Start();
virtual int Work() = 0;
protected:
void Run();
boost::thread thread_;
};
//---------------------------------------------------------------------------------------------------------------------------------------------
// BaseThread.cpp
#include "BaseThread.h"
//------------------------------------------------------------------------------
BaseThread::BaseThread()
{
}
//------------------------------------------------------------------------------
BaseThread::~BaseThread()
{
// Wait for the thread to complete
thread_.join();
// DEBUG - Does join wait?
int x = 1;
}
//------------------------------------------------------------------------------
void BaseThread::Start()
{
boost::thread newThread(boost::bind(&BaseThread::Run, this));
thread_.swap(newThread);
}
//------------------------------------------------------------------------------
void BaseThread::Run()
{
this->Work();
}
I am kind of winging it here just going off of the boost documentation
and guessing at what I should be doing. This code has a problem in
that in order for us to wait for the thread to complete, the derived
class is going to have to call thread_.join(). That leaves a bad taste
in my mouth as I'd rather the base class take care of all the details,
and all the derived class has to worry about is providing a Work
method.
This class doesn't provide much that boost::thread doesn't already
have, but I want to make different classes for additonal requirements.
One of which I have in mind is a thread with looped work and a start,
stop, method.
Making an object out of it will also probably help with derving
classes that take care of locking their data...or at least organize it
a bit.
So the question is, is there a way I can avoid the requirement here
that derived classes call thread_.join() and do something different in
the base class?
I'll probably have more questions as I progress.