1

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.

Community
  • 1
  • 1
Ennosigaeon
  • 442
  • 7
  • 15
  • 5
    _' This question is quite similar, but the answers didn't solve my problem.'_ Why? I'd also urgently recommend to use a plain `std::thread` member, instead of a `std::thread*` pointer. – πάντα ῥεῖ May 02 '14 at 14:45
  • 3
    Why are you using a pointer to `std::thread` and taking the address of a temporary? (which should have caused a compilation error) – David G May 02 '14 at 14:46

2 Answers2

10

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
}
W.B.
  • 5,445
  • 19
  • 29
1

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.

sfjac
  • 7,119
  • 5
  • 45
  • 69