简体   繁体   English

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

[英]SIGABRT signal received when creating a std::thread c++11

I create a thread in a class member method like this: 我在类成员方法中创建一个线程,如下所示:

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

void MyClass::myThreadMethod()
{
    // ...
}

where 哪里

// In header file
std::unique_ptr<std::thread> T;

When I run MyClass::startThread() , I receive this: 当我运行MyClass::startThread() ,我会收到:

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

If I step the code, it happens in the thread constructor. 如果我执行代码,它会在线程构造函数中发生。

I tried to removed the unique_ptr like this: 我试图像这样删除unique_ptr

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

and the same thing occurred. 并发生了同样的事情。 I use gcc 4.8.2 on NetBeans 7.4 on Linux/Kubuntu 12.04. 我在Linux / Kubuntu 12.04上的NetBeans 7.4上使用gcc 4.8.2。

Someone knows what happens? 有人知道会发生什么吗?

This happens when an std::thread is destroyed without a prior call to std::thread::detach() or std::thread::join() . 当没有事先调用std::thread::detach()std::thread::join()而销毁std::thread时会发生这种情况。 You should call either of the two, and what to call depends on your desired behavior. 你应该调用两者中的任何一个,调用什么取决于你想要的行为。

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

or 要么

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)
}

As a side note, you can remove your use of std::unique_ptr by making the std::thread itself a member: 作为旁注,您可以通过使std::thread本身成为成员来删除对std::unique_ptr的使用:

class MyClass {
    std::thread t;
};

To assign t a thread, you can construct one and move assign it to t : 要分配t一个线程,你可以构建一个与移动它分配给t

t = std::thread(&MyClass::myThreadMethod, this);

According to Mark Garcia suggestion and example, and according to this question I just added -pthread as option to the compiler. 根据Mark Garcia的建议和示例,根据这个问题,我刚刚添加了-pthread作为编译器的选项。

For an unknown reason, my other projects work correctly but I believe that it is due to Boost or Open CV that must include something that was missing from this current test. 由于未知原因,我的其他项目正常工作,但我认为这是由于Boost或Open CV必须包含当前测试中缺少的内容。

Anyway, for the moment, it works. 无论如何,目前,它的工作原理。

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM