c++ - std::notify_all_at_thread_exit 是如何工作的?

标签 c++ multithreading c++11 standards language-implementation

根据 cppref :

std::notify_all_at_thread_exit provides a mechanism to notify other threads that a given thread has completely finished, including destroying all thread_local objects.

我知道 std::notify_all_at_thread_exit 的确切语义。让我不解的是:

如何注册在给定线程完成并销毁其所有线程局部对象后调用的回调函数?

最佳答案

std::notify_all_at_thread_exit 通过引用在其第一个参数中采用条件变量。当线程退出时,它将对该条件变量调用notify_all,唤醒等待条件变量被通知的线程。

似乎没有直接的方法来真正为此注册回调;你可能需要有一个线程等待条件变量被通知(使用与传递到 std::notify_all_at_thread_exit 的锁相同的锁)。当 CV 被通知时,正在等待的线程应该验证唤醒不是虚假的,然后执行应该运行的所需代码。

有关如何实现的更多信息:
至少在 Google's libcxx , std::notify_all_at_thread_exit电话 __thread_struct_imp::notify_all_at_thread_exit ,它将带有参数的对存储到 vector (_Notify)。线程死亡后,destructor __thread_struct_imp 迭代这个 vector 并通知所有以这种方式注册的条件变量。

与此同时,GNU stdc++ 使用类似的方法:创建一个 notifier 对象,将其注册到 __at_thread_exit,它被设计为在线程退出时调用其析构函数,并且析构函数实际上执行通知过程。我需要更仔细地调查 __at_thread_exit,因为我还没有完全理解它的内部工作原理。

关于c++ - std::notify_all_at_thread_exit 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52138149/

相关文章:

python - Python 中的多处理比单线程慢

c++ - 继承和 friend : Safety mechanism?

c++ - 在 VC2015 中连接不匹配的字符串 WORKS - 如何?

按非类型参数类型的 C++ 模板特化

java - 观察者模式 Java - 使用线程的多个观察者

c++ - QT QImageReader setScaledSize 与 setAutoTransform 交互

python - 多处理列表中的多个文件

c++ - 允许 tr1::function 吞下返回值的解决方法

c++ - 一个关于C++虚函数的问题

c++ - 恒定时间访问是否​​意味着在某些时候是连续的内存?