简体   繁体   中英

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:

Signal received: SIGABRT (Aborted) ...

If I step the code, it happens in the thread constructor.

I tried to removed the unique_ptr like this:

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.

Someone knows what happens?

This happens when an std::thread is destroyed without a prior call to std::thread::detach() or std::thread::join() . 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:

class MyClass {
    std::thread t;
};

To assign t a thread, you can construct one and move assign it to 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.

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.

Anyway, for the moment, it works.

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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