(简单)提升thread_group问题

Ran*_*Guy 24 c++ multithreading boost boost-thread

我正在尝试编写一个相当简单的线程应用程序,但它是boost的线程库的新手.我正在研究的一个简单的测试程序是:

#include <iostream>
#include <boost/thread.hpp>

int result = 0;
boost::mutex result_mutex;

boost::thread_group g;

void threaded_function(int i)
{
    for(; i < 100000; ++i) {}

    {
        boost::mutex::scoped_lock lock(result_mutex);
        result += i;
    }
}

int main(int argc, char* argv[])
{
    using namespace std;

    // launch three threads
    boost::thread t1(threaded_function, 10);
    boost::thread t2(threaded_function, 10);
    boost::thread t3(threaded_function, 10);

    g.add_thread(&t1);
    g.add_thread(&t2);
    g.add_thread(&t3);

    // wait for them
    g.join_all();

    cout << result << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我编译并运行该程序时,我得到了一个输出

$ ./test 
300000
test: pthread_mutex_lock.c:87: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed.
Aborted
Run Code Online (Sandbox Code Playgroud)

显然,结果是正确的,但我担心这个错误信息,特别是因为具有基本相同结构的真实程序被卡在join_all()点.有人可以向我解释发生了什么吗?有没有更好的方法来执行此操作,即启动多个线程,将它们存储在外部容器中,然后在继续执行程序之前等待它们全部完成?

谢谢你的帮助.

Voi*_*ter 29

我认为你的问题是由你的程序退出时调用的thread_group析构函数引起的.线程组想要负责破坏你的线程对象.另请参见boost :: thread_group文档.

您正在堆栈中创建线程对象作为main函数范围内的局部变量.因此,当程序退出并且thread_group尝试删除它们时,它们已被破坏.

作为解决方案,使用new在堆上创建线程对象,让thread_group处理它们的破坏:

boost::thread *t1 = new boost::thread(threaded_function, 10);
...
g.add_thread(t1);
...
Run Code Online (Sandbox Code Playgroud)


小智 27

如果您不需要线程句柄,请尝试使用thread_group :: create_thread(),这样可以减少管理线程的需要:

// Snip: Same as previous examples

int main(int argc, char* argv[])
{
    using namespace std;

    // launch three threads
    for ( int i = 0; i < 3; ++i )
        g.create_thread( boost::bind( threaded_function, 10 ) );

    // wait for them
    g.join_all();

    cout << result << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)