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.

2
  • 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. Commented May 2, 2014 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) Commented May 2, 2014 at 14:46

2 Answers 2

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 } 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.