为什么 boost::thread 的析构函数分离可连接线程,而不是按照标准建议调用 Terminate() ?
根据 C++0x 标准草案,此代码:
void simplethread()
{
boost::thread t(someLongRunningFunction);
// Commented out detach - terminate() expected.
// t.detach();
}
... 应该导致 Terminate() 调用,但在 boost 线程的当前(boost 1.46.1)实现中却没有,线程只是在析构函数中分离,并且继续。
我的问题是:为什么?
我认为 boost::thread 与草案标准尽可能一致。
这有设计原因吗? boost::thread 的未来版本会改变吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
原因很大程度上是历史原因。
boost::thread
首先出现。std::thread
的提案源自boost::thread
,最初具有boost::thread
现在的行为。然而,在标准化过程中,很多人希望在析构函数中使用
std::thread::~thread()
(如果尚未加入)join()
,而不是 <代码>分离()。双方都进行了辩论并进行了投票。 50/50。提出了更多的论点并进行了更多的投票。有些人转向了另一个立场。但仍然是 50/50。有人(我不记得是谁)建议
terminate()
。进行了投票,虽然它没有得到一致赞成(我不能投票赞成),但它确实获得了足够的多数票,可以称为共识。我想 boost::thread 永远不会改变,因为它有一个已安装的用户群,并且没有人希望不必要地破坏该用户群的代码。
编辑:
啊,罗布向我们指出了这个重复问题的原文,
答案指向 N2802 其中包括基本原理。
我还应该注意到,std::thread 的原始提案具有线程取消功能,而 ~thread() 会取消未连接的线程,然后将其分离,这很有意义。通常只有当父线程由于异常而展开时才会选择此代码路径。
The reason is largely historical.
boost::thread
came first. The proposals forstd::thread
were derived fromboost::thread
and originally had the behavior thatboost::thread
does now.However during the standardization process a significant number of people wanted
std::thread::~thread()
tojoin()
in the destructor if not already joined, instead ofdetach()
. 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.