C++ – std::thread crashes upon execution

Destroying a std::thread object associated with a joinable() thread causes std::terminate() to be called. §30.3.1.3 [thread.thread.destr]:

~thread();

If joinable(), calls std::terminate(). Otherwise, has no
effects. [ Note: Either implicitly detaching or joining a joinable()
thread in its destructor could result in difficult to debug
correctness (for detach) or performance (for join) bugs encountered
only when an exception is raised. Thus the programmer must ensure that
the destructor is never executed while the thread is still joinable.
end note ]

There are a multitude of possible fixes:

  • Allocate the thread on the heap and having your function return a smart pointer to the thread object
  • Or have it return a std::thread (move serverConnect into the return value)
  • Move serverConnect into something that won’t be destroyed when connectToServer() returns (e.g., a global variable)
  • join() the thread before you return
  • detach() the thread before you return

The correct choice depends on your particular use case.

Leave a Comment