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>

class Callable
int value_;
Callable(int value) : value_(value) {}

void operator()()
std::cout << "cout down ";
while(value_ > 0)
std::cout << value_ << ' ';
std::cout << "done" << std::endl;

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

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

std::cout << "Secondary thread joined" << std::endl;

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

std::cout << "Secondary thread detached" << std::endl;
std::cout << "Done thread testing" << std::endl;

No comments:

Post a Comment