简体   繁体   English

如何在调用pthread_cond_destroy之前发出信号以中止/唤醒所有等待条件变量的线程?

[英]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(). 我知道当有1个以上的线程在等待条件变量时调用pthread_cond_destroy()时会发生不确定的行为,并且我正在寻找一种变通方法,以便在调用pthread_cond_destroy()之前向所有等待条件变量的线程发送唤醒信号

My CV class destructor calls pthread_cond_destroy() if condition variable is valid. 如果条件变量有效,我的CV类析构函数将调用pthread_cond_destroy()。 Therefore, I thought of: 因此,我想到了:

  1. Broadcasting before calling pthread_cond_destroy() but that would wake just 1 thread. 在调用pthread_cond_destroy()之前进行广播,但这只会唤醒1个线程。 I want destructor to succeed and that no thread should be able to wait on the cv object (No dereferencing on destructed object). 我希望析构函数成功执行,并且没有线程应该能够在cv对象上等待(在析构对象上不进行解引用)。

  2. Is signal counting (along with workaround #1) a way to fix this issue? 信号计数(以及变通方法1)是否可以解决此问题? If so, how do I ensure that all waiting threads have been scheduled (woken up) before ~CV() succeeds? 如果是这样,我如何确保在〜CV()成功之前已计划(唤醒)所有等待线程?

  3. Do I overcome this issue if I use C++ 11 thread/condition variable? 如果使用C ++ 11线程/条件变量,是否可以解决此问题?

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) 调用pthread_cond_broadcast()唤醒所有线程(以便他们可以检查该标志,查看该标志是否已设置并通过干净退出进行响应)
  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 在每个线程上调用pthread_join(),这样您将知道它们都已消失,因此继续进行下一步是安全的
  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) 调用pthread_cond_destroy()销毁您的条件变量(现在可以安全地执行此操作,因为您知道没有线程在使用它,因为它们都在第3步完成之前退出了)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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