Ennosigaeon
Ennosigaeon

Reputation: 442

C++11: Start thread in object with member function and this

I have the follwing three files:

MyClass.h

class MyClass {
private:
    std::thread* thread = NULL;
    void run();
public:
    ~MyClass();
    void start();
}

MyClass.cpp

MyClass:~MyClass() {
    if (thread != NULL)
        thread -> join();
}

void MyClass::run() {
    //do stuff
}

void MyClass::start() {
    thread = &std::thread (&MyClass::run, this);
}

Main.cpp

int main() {
    MyClass obj{};
    obj.start();
    return 0;
}

When I run this code I always get R6010 - abort() has been called and I don't know why abort() is called. When I create the thread in the main function it works, but for design reasons I want to start it in MyClass. This there a way to start the thread in MyClass?

P.S.: This question is quite similar, but the answers didn't solve my problem.

Upvotes: 1

Views: 3500

Answers (2)

sfjac
sfjac

Reputation: 7304

You need to either keep a std::thread member or use new to create the thread pointer. As it is, your std::thread object is going out of scope at the end of start() and that results in terminate being called on the thread.

Upvotes: 1

W.B.
W.B.

Reputation: 5525

That's because the handle to std::thread is destroyed (goes out of scope) before it's either joined or detached.

I suggest:

class MyClass {
private:
    std::thread thread;
    void run();
public:
    ~MyClass();
    void start();
}

and:

MyClass:~MyClass() {
    if (thread.joinable())
        thread.join();
}

void MyClass::run() {
    //do stuff
}

void MyClass::start() {
    thread = std::thread (&MyClass::run, this); //Move assignment
}

Upvotes: 10

Related Questions