Why .join is still necessary when all other thread have finished before the main thread?

前端 未结 4 611
忘了有多久
忘了有多久 2021-02-06 09:13

Learning C++ multi-threading.
In my example, thread helper1 and helper2 have finished executing before the main thread finished. Howev

4条回答
  •  醉话见心
    2021-02-06 10:04

    Because std::~thread calls terminate if the associated thread is still joinable:

    30.3.1.3 thread destructor [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]

    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.

提交回复
热议问题