std thread creation - destructor crash when not assigned to a variable

Can someone please explain to me how I can get a crash in the destructor of std::thread when I don't assign std::thread constructor return value to a variable?
1
2
3
4
5
6
7
8
9
10
11
int main(int argc, char** argv) {
  ...

  // This works, assigning thread to a variable
  std::thread thr = std::thread(&my_thread_main::start, (void*) arg);

  // If no assignment to variable - crash in thread destructor
  // std::thread(&my_thread_main::start, (void*) arg);

  return 0;
}



line 148 ~thread()
line 149 {
line 150 if (joinable())
------------> line 151 std::terminate();
line 152 }
line 153
Last edited on
If a std::thread object is still associated with an actual thread when it is destroyed,
the destructor calls std::terminate()

To disassociate the actual thread of execution from the anonymous std::thread object,
we can call detach() on it. std::thread( &my_thread_main::start, (void*) arg).detach() ;
get a crash in the destructor of std::thread when I don't assign std::thread constructor return value to a

variable?

I'm not even sure what it means to assign the return value of a std::thread ctor because unlike std::future, std::thread doesn't return any values but you need to do one of two things - either:
(a) thread.join() that waits for the thread to finish and blocks until then, or
(b) thread.detach() that detaches the functionality (function, member function, function object, lambda) passed to the thread from the std::thread object and lets it run in the backgroun without any control.
If you don't do this before the lifetime of the thread object ends or a move assignment to it happens, the program aborts, calling std::terminate() ... (i)f you let the thread run in the background and main() ends, all threads are terminated abruptly
- Section 18.2.1, "The C++ Standard Library", Nicolai Josuttis (2nd ed)
Last edited on
Topic archived. No new replies allowed.