【问题标题】:How does std::notify_all_at_thread_exit work?std::notify_all_at_thread_exit 是如何工作的?
【发布时间】:2018-09-02 14:54:47
【问题描述】:

根据cppref

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    有关如何实施的更多信息:
    至少在Google's libcxxstd::notify_all_at_thread_exit 调用__thread_struct_imp::notify_all_at_thread_exit,它将带有参数的一对存储到向量(_Notify)。在线程死亡时,__thread_struct_impdestructor 会遍历这个向量,并通知所有以这种方式注册的条件变量。

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

    【讨论】:

    • 如何保证notify_all会在所有线程本地对象被销毁后被调用?如何在 Linux/Windows 下实现?
    • @xmllmx 我在帖子中添加了一个标准库实现如何实现这一目标的概述。
    猜你喜欢
    • 2013-06-15
    • 2012-12-15
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    相关资源
    最近更新 更多