Delayed start of a boost::thread

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

On 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;

class ThreadSomething
boost::thread t_;
int sec_;

void doSomething(int sec)
cout << boost::this_thread::get_id() << ": doing something" << endl;

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

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

void 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;

cout << boost::this_thread::get_id() << ": joining" << endl;
cout << boost::this_thread::get_id() << ": done" << endl;

No comments:

Post a Comment