Launching a boost::thread

To create a new boost::thread object, an object of a callable type that could be invoked passing no parameter should be passed to its constructor.

The object passed to the boost::thread constructor is copied to the thread local memory and invoked in its specific execution thread.

If it is not possible to copy the callable object, we could use std::ref (or boost::ref) to use a reference in the new thread. In this case, the caller must ensure the callable object being alive until the newly created thread terminate.

As example we use a class, Callable, to show the different behaviour creating a thread passing an object in the default way (copy) and by std::ref.

The copy constructor of Callable set its internal control variable to zero, whatever is the original one. So we could have easily a direct feedback on what is happening internally.


#include <iostream>
#include <boost/thread.hpp>

namespace
{
class Callable
{
private:
int value_;
public:
Callable(int value) : value_(value) {}
Callable(const Callable& c) { value_ = 0; }

void operator()()
{
std::cout << "count down ";
while(value_ > 0)
{
std::cout << value_ << ' ';
boost::this_thread::sleep(boost::posix_time::seconds(1));
--value_;
}
std::cout << "done" << std::endl;
}
};
}

void t01()
{
std::cout << "Launching threads" << std::endl;

Callable c1(12);
boost::thread t1(c1);
t1.join();

Callable c2(12);
boost::thread t2(std::ref(c2));
t2.join();

std::cout << "Done thread testing" << std::endl;
}

No comments:

Post a Comment