从线程调用 add_thread 时,Boost thread_group 会阻塞,为什么?
我编写了一个类似于以下结构的多线程程序(我省略了互斥锁和无关代码),并且当从 a 调用时,它会阻止对 boost::thread_group.add_thread() 的调用线。有什么办法可以解决这个问题,这样调用就不会阻塞吗?
boost::thread_group group;
void threaded_function2()
{
}
void threaded_function()
{
if( condition)
{
boost::thread *t3 = new boost::thread( boost::bind( &threaded_function2));
group.add_thread( t3); // <-- Blocks on this call
}
}
int main()
{
boost::thread *t1 = new boost::thread( boost::bind( &threaded_function));
boost::thread *t2 = new boost::thread( boost::bind( &threaded_function));
group.add_thread( t1);
group.add_thread( t2);
group.join_all();
return 0;
}
谢谢大家。
I've written a multithreaded program similar to the following structure (I've omitted the mutex and extraneous code), and it blocks on the call to boost::thread_group.add_thread()
when called from a thread. Is there any way around this, so the call doesn't block?
boost::thread_group group;
void threaded_function2()
{
}
void threaded_function()
{
if( condition)
{
boost::thread *t3 = new boost::thread( boost::bind( &threaded_function2));
group.add_thread( t3); // <-- Blocks on this call
}
}
int main()
{
boost::thread *t1 = new boost::thread( boost::bind( &threaded_function));
boost::thread *t2 = new boost::thread( boost::bind( &threaded_function));
group.add_thread( t1);
group.add_thread( t2);
group.join_all();
return 0;
}
Thanks everyone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我错了,请纠正我,但这里可能发生的情况是 join_all 调用在添加线程之前运行,使得 thread_group 对象阻塞,直到其他线程被释放。一种解决方案是在 main 函数上创建一个互斥体,以等待 threaded_function 完成后调用 join_all 方法。但这是一个糟糕的设计。
Correct me if I'm wrong, but what might be happening here is that the join_all call ran before the thread getting added, making the thread_group object block until the other threads are released. One solution is to make a mutex on the main function to wait for the threaded_function completes to call the join_all method. This is bad design, though.