According to the draft C++0x standard, this code:
void simplethread()
{
boost::thread t(someLongRunningFunction);
// Commented out detach - terminate() expected.
// t.detach();
}
... should result in an terminate() call, but in current (boost 1.46.1) implementation of boost threads it doesn't, thread simply gets detached in destructor and continues on.
My question is: why?
I thought boost::thread is as much inline with draft standard as it gets.
Is there a design reason for this? Will it be changed in future versions of boost::thread?
thread::detachSeparates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits.
Detach thread. Detaches the thread represented by the object from the calling thread, allowing them to execute independently from each other. Both threads continue without blocking nor synchronizing in any way. Note that when either one ends execution, its resources are released.
If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything.
When a thread is created, one of its attributes defines whether it is joinable or detached. Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined.
The reason is largely historical. boost::thread
came first. The proposals for std::thread
were derived from boost::thread
and originally had the behavior that boost::thread
does now.
However during the standardization process a significant number of people wanted std::thread::~thread()
to join()
in the destructor if not already joined, instead of detach()
. The arguments were made for each side and the votes were taken. 50/50. More arguments were made and more votes were taken. Some people were swayed to the other position. But still 50/50.
Someone (I don't recall who) suggested terminate()
. Votes were taken and though it wasn't unanimous in favor (I couldn't vote for it), it did receive enough of a majority to be called consensus.
I imagine boost::thread
never changed because it had an installed user base and no one wants to unnecessarily break code for that user base.
Edit:
Ah, Rob points us to the original of this duplicate question and that answer points to N2802 which includes rationale.
I should also note that the original proposal for std::thread
had thread cancellation, and ~thread() would cancel the unjoined-thread and then detach it, which made a lot of sense. This code path would normally only be chosen when the parent thread was unwinding due to an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With