lau*_*ura 9 c++ multithreading boost deadlock
我看到一个问题,在析构函数中调用boost的thread-> join会导致死锁.我不明白为什么,而且我不太热衷于保持代码在项目中正常工作(我不明白为什么会这样).
类声明(我为了简洁而剥离了try/catch的run()方法:根据boost线程文档,结果应该是相同的,有或没有):
class B
{
public:
void operator()(){run();}
void run();
void shutdown();
~B();
B();
boost::thread *thr;
bool shutdown_requested;
};
void B::shutdown()
{
shutdown_requested = true;
if (thr != NULL)
{
thr->interrupt();
thr->join(); // deadlock occurs here!
delete thr;
thr = NULL;
}
}
B::~B()
{
shutdown();
}
B::B()
{
thr = new boost::thread(boost::ref(*this));
}
void B::run()
{
while (!shutdown_requested)
{
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += 30;
boost::this_thread::sleep(xt);
}
}
Run Code Online (Sandbox Code Playgroud)
片段不起作用:
int main()
{
B *b = new B;
Sleep(5000);
printf("deleting \n");fflush(stdout);
// b->shutdown();
delete b;
printf("done\n");fflush(stdout);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
工作的片段:
int main()
{
B *b = new B;
Sleep(5000);
printf("deleting \n");fflush(stdout);
b->shutdown();
delete b;
printf("done\n");fflush(stdout);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我认为这种行为的原因与boost文档的这个片段有关:
Boost.Thread的用户必须确保引用的对象超过新创建的执行线程.
但我真的不明白为什么死锁 - 加入线程不会调用B上的析构函数,并且当run()方法应该退出时,对象本身不会被删除.
我发现了这个问题:它归结为一个过于热心的程序员。
我最初使用 DUMA ( http://sourceforge.net/projects/duma/ )编译了我的项目,以查看当前模块的实现是否无泄漏。不幸的是,我的测试沙箱也启用了杜马设置,直到我在调试器中单步执行代码时我才意识到这一点。
删除所有内存泄漏检测后,一切都按预期进行。