Learning C++ multi-threading.
In my example, thread helper1
and helper2
have finished executing before the main
thread finished. Howev
Because std::~thread
calls terminate
if the associated thread is still joinable:
30.3.1.3 thread destructor [thread.thread.destr]
~thread();
If
joinable()
, callsstd::terminate()
. Otherwise, has no effects. [ Note: Either implicitly detaching or joining ajoinable()
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]
You need to call either .detach()
or .join()
. Other than that, since you cannot be sure how the operating system schedules your threads, you could end up interrupting your threads any way, so better use .join()
from the beginning.