Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::thread thread spun off in object, when does it terminate?

If I spin off an std::thread in the constructor of Bar when does it stop running? Is it guaranteed to stop when the Bar instance gets destructed?

class Bar {

public:

Bar() : thread(&Bar:foo, this) {
}

...

void foo() {
  while (true) {//do stuff//}

}

private:
  std::thread thread;

};

EDIT: How do I correctly terminate the std::thread in the destructor?

like image 229
user695652 Avatar asked Mar 29 '26 18:03

user695652


1 Answers

If I spin off an std::thread in the constructor of Bar when does it stop running?

the thread will run as long as it executing the callable you provided it, or the program terminates.

Is it guaranteed to stop when the Bar instance gets destructed?

No. In order to guarantee that, call std::thread::join in Bar destructor.

Actually, if you hadn't call thread::join or thread::detach prior to Bar::~Bar, than your application will be terminated by calling automatically to std::terminate. so you must call either join (preferable) or detach (less recommended).

you also want to call therad::join on the object destructor because the spawned thread relies on the object to be alive, if the object is destructed while your thread is working on that object - you are using destructed object and you will have undefined behavior in your code.

like image 154
David Haim Avatar answered Apr 02 '26 04:04

David Haim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!