Pages

Joining and detaching a boost::thread

Our thread has launched another thread. There are a couple of things that now it could do with it now: wait for its termination or let it go.

If we don't have anything more interesting to do in the current thread, we can let it waiting for some times for the other thread, using timed_join().

Or could wait indefinitely for it, by calling join().

A third alternative is detaching the thread from the boost::thread object. In this way we are saying that we don't want to have anything to do anymore with that thread. It would do its job till the end, and we were not concerned with its life and death.

Here is a short example showing what said:

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

namespace
{
class Callable
{
private:
int value_;
public:
Callable(int value) : value_(value) {}

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

void t02()
{
std::cout << "Launching a thread" << std::endl;

boost::thread t1(Callable(6));
t1.timed_join(boost::posix_time::seconds(2));
std::cout << std::endl << "Expired waiting for timed_join()" << std::endl;

t1.join();
std::cout << "Secondary thread joined" << std::endl;

Callable c2(3);
boost::thread t2(c2);
t2.detach();

std::cout << "Secondary thread detached" << std::endl;
boost::this_thread::sleep(boost::posix_time::seconds(5));
std::cout << "Done thread testing" << std::endl;
}

No comments:

Post a Comment