简体   繁体   中英

How do I signal to abort/wake all threads waiting on a condition variable before calling pthread_cond_destroy?

I'm aware of undefined behavior on calling pthread_cond_destroy() when there is 1+ thread waiting on a condition variable and I'm looking for a workaround to send wake signal to all threads waiting on a condition variable before calling pthread_cond_destroy().

My CV class destructor calls pthread_cond_destroy() if condition variable is valid. Therefore, I thought of:

  1. Broadcasting before calling pthread_cond_destroy() but that would wake just 1 thread. I want destructor to succeed and that no thread should be able to wait on the cv object (No dereferencing on destructed object).

  2. Is signal counting (along with workaround #1) a way to fix this issue? If so, how do I ensure that all waiting threads have been scheduled (woken up) before ~CV() succeeds?

  3. Do I overcome this issue if I use C++ 11 thread/condition variable?

Here's how I would do it (assuming you want to destroy the condition variable because you're cleanup up and want the threads to exit; if you don't want the threads to exit, then you shouldn't destroy the condition variable they are using):

  1. Set a boolean flag (or something) that indicates that you want all of the threads to go away
  2. Call pthread_cond_broadcast() to wake up all the threads (so that they can check the flag, see that it is set, and respond by exiting cleanly)
  3. call pthread_join() on each of the threads, so that you'll know they are all gone and it is therefore safe to continue on to the next step
  4. call pthread_cond_destroy() to destroy your condition variable (now safe to do because you know there are no threads using it, because they all exited before step 3 completed)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM