What happens when calling the destructor of a thread object that has a condition variable waiting?

后端 未结 3 1641
遇见更好的自我
遇见更好的自我 2020-12-06 02:38

I am using a SynchronisedQueue to communicate between threads. I found that destroying the thread object when the attaching thread is waiting on a condition var

相关标签:
3条回答
  • 2020-12-06 03:22

    From the C++11 spec:

    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 pro grammer must ensure that the destructor is never executed while the thread is still joinable. — end note ]

    So calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.

    0 讨论(0)
  • 2020-12-06 03:23

    The destructor for std::thread will call std::terminate if it is run on a thread if you not have called join() (to wait the thread to finish) or detach() (to detach the thread from the object) on it.

    Your code calls the destructor for worker_thread without calling join() or detach() on it, and so std::terminate is called. This is unrelated to the presence of condition variables.

    0 讨论(0)
  • 2020-12-06 03:28

    You cannot, ever, destroy a resource while something is, or might be, using it. That's really just common sense.

    0 讨论(0)
提交回复
热议问题