Delayed start of a boost::thread

A nuisance of boost::thread is that as we create the instance, the new thread starts.

On antonym.org there is an interesting post on boost::thread creation that ends suggesting the creation of a wrapper class to solve this issue.

We use the fact that a boost::thread could be created without passing anything to the constructor, and in this case the object would be in a not-a-thread status. We will explicitly run the thread calling a start() method in our wrapper class, that creates a new boost::thread and assigns it to the member one.

Here is an example:

#include <iostream>
#include "boost\thread\thread.hpp"

using std::cout;
using std::endl;

namespace
{
class ThreadSomething
{
private:
boost::thread t_;
int sec_;

void doSomething(int sec)
{
cout << boost::this_thread::get_id() << ": doing something" << endl;
boost::this_thread::sleep(boost::posix_time::seconds(sec));
}

public:
ThreadSomething(int sec) : sec_(sec) {}

void start()
{
t_ = boost::thread(&ThreadSomething::doSomething, this, sec_);
}

void join()
{
t_.join();
}
};
}

void t06()
{
cout << boost::this_thread::get_id() << ": creating a new thread" << endl;
ThreadSomething ts(2);

cout << boost::this_thread::get_id() << ": starting a new thread" << endl;
ts.start();

cout << boost::this_thread::get_id() << ": joining" << endl;
ts.join();
cout << boost::this_thread::get_id() << ": done" << endl;
}

No comments:

Post a Comment