创建std :: thread c ++ 11时收到的SIGABRT信号

dom*_*eau 6 c++ multithreading gcc stl c++11

我在类成员方法中创建一个线程,如下所示:

void MyClass::startThread()
{
    T.reset( new std::thread( &MyClass::myThreadMethod, this ) );
}

void MyClass::myThreadMethod()
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

哪里

// In header file
std::unique_ptr<std::thread> T;
Run Code Online (Sandbox Code Playgroud)

当我跑步时MyClass::startThread(),我会收到:

收到的信号:SIGABRT(已中止)......

如果我执行代码,它会在线程构造函数中发生.

我试图删除unique_ptr这样的:

void MyClass::startThread()
{
    std::thread* T = new std::thread( &MyClass::myThreadMethod, this );
}
Run Code Online (Sandbox Code Playgroud)

并发生了同样的事情.我在Linux/Kubuntu 12.04上的NetBeans 7.4上使用gcc 4.8.2.

有人知道会发生什么吗?

Mar*_*cia 13

这种情况发生在std::thread没有事先调用std::thread::detach()或被破坏的情况下std::thread::join().你应该调用两者中的任何一个,调用什么取决于你想要的行为.

void MyClass::startThread() {
    T.reset( new std::thread( &MyClass::myThreadMethod, this ) );
    T->join();  // Wait for thread to finish
}
Run Code Online (Sandbox Code Playgroud)

要么

void MyClass::startThread() {
    T.reset( new std::thread( &MyClass::myThreadMethod, this ) );
    T->detach();  // Leave thread on its own (do not wait for it to finish)
}
Run Code Online (Sandbox Code Playgroud)

作为附注,您可以std::unique_ptr通过使std::thread自己成为成员来删除您的使用:

class MyClass {
    std::thread t;
};
Run Code Online (Sandbox Code Playgroud)

要分配t一个线程,您可以构建一个线程并将其分配给t:

t = std::thread(&MyClass::myThreadMethod, this);
Run Code Online (Sandbox Code Playgroud)

  • @dom_beau我做了[测试](http://coliru.stacked-crooked.com/a/839988ed13bedebf),表明问题是通过使用detach或join来解决的.当然,对于(2),通常会为长时间运行的操作调用join,因此立即调用它会使执行有效地同步.以上仅供演示.(3)你可能正在为你的`std :: thread`分配另一个线程,这样做会破坏前一个对象(例如在已经包含`std :: thread`的`unique_ptr`上调用`.reset`). (2认同)

dom*_*eau 5

根据Mark Garcia的建议和示例,根据这个问题,我刚刚添加-pthread了编译器的选项.

由于未知原因,我的其他项目正常工作,但我认为这是由于Boost或Open CV必须包含当前测试中缺少的内容.

无论如何,目前,它的工作原理.

谢谢!