【问题标题】:Boost thread_group blocks when calling add_thread from thread, why?从线程调用 add_thread 时提升 thread_group 块,为什么?
【发布时间】:2011-10-22 22:56:25
【问题描述】:

我编写了一个类似于以下结构的多线程程序(我省略了互斥锁和无关代码),当从线程调用时,它会阻塞对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;
}

谢谢大家。

【问题讨论】:

    标签: c++ multithreading boost boost-thread


    【解决方案1】:

    如果我错了,请纠正我,但这里可能发生的是 join_all 调用在线程被添加之前运行,使得 thread_group 对象阻塞,直到其他线程被释放。一种解决方案是在 main 函数上创建一个互斥体,以等待 threaded_function 完成以调用 join_all 方法。不过,这是糟糕的设计。

    【讨论】:

    • 这就是发生的事情,我意识到如果它不起作用,那一定是一个糟糕的设计,所以我将我的设计重构为一个更加流畅的结构,仍然可以满足我的需求。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-02-28
    • 2014-04-13
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多