std :: notify_all_at_thread_exit如何工作?

问题描述 投票:2回答:1

cppref说:

std::notify_all_at_thread_exit提供了一种机制来通知其他线程给定线程已完全完成,包括销毁所有thread_local对象。

我知道std::notify_all_at_thread_exit的确切语义。令我困惑的是:

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

c++ multithreading c++11 standards language-implementation
1个回答
2
投票

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,它将一对参数存储到矢量(_Notify)。线程死亡后,destructor__thread_struct_imp迭代此向量并通知以这种方式注册的所有条件变量。

同时,GNU stdc ++使用了类似的方法:创建了一个notifier对象,它在__at_thread_exit中注册,它被设计为在线程出口运行时调用它的析构函数,析构函数实际执行通知过程。我需要更密切地调查__at_thread_exit,因为我还没完全理解它的内部工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.