Sign in to follow this  
i_is_want_smart

boost::thread

Recommended Posts

I've just been toying around with the boost/thread library, and I encountered a problem. After a thread is created, there seems to be no way of terminating it except by returning from within the thread function. I've written threads with win32 before and I know there is a TerminateThread function. Is there a boost::thread equivalent?

Share this post


Link to post
Share on other sites
If you're doing RAII using a boost::shared_ptr<boost::thread> then you don't need a terminator, exiting is just fine. Reference count on the thread will be adjusted internally for you and destroyed if needed ;-)

And if you're not doing RAII, then you should revise and do :-D

Cheers

Share this post


Link to post
Share on other sites
In what situation have you called TerminateThread in the past, you have to know the ins and outs of what the thread is doing and the resources it can control to call this function. In the words of Mr Mackey "TerminateThread is bad".

Share this post


Link to post
Share on other sites
Quote:
Original post by i_is_want_smart
I've just been toying around with the boost/thread library, and I encountered a problem. After a thread is created, there seems to be no way of terminating it except by returning from within the thread function.


Yes, that's the appropriate method of exiting a thread.


volatile bool running;

void thread_func() {
while (running) {
// foo
}
};

....
running = true;
boost::thread t(&thread_func());
...

running = false;
t.join();


Terminate thread usually indicates inadequate flow control. There's effectively never a situation where one would want to force a thread to terminate.

Share this post


Link to post
Share on other sites
The boost thread library since 1.35 has a feature to interrupt threads. This is a much better alternative.

A boost::thread_interrupted exception will be thrown at the next interruption point inside your thread. This gives your destructors an opportunity to clean up, which naive thread termination does not.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this