如何在线程退出时触发代码,而不使用函数 *_at_thread_exit

How to trigger code when a thread exits, without using functions *_at_thread_exit?

本文关键字:函数 thread at exit 线程 退出 代码      更新时间:2023-10-16

假设我的应用程序中有两个线程,我需要在另一个线程退出时通知我的主线程。

我知道 C++11 提供了 std::notify_all_at_thread_exit()std::promise::set_{value,exception}_at_thread_exit() ,这正是我正在寻找的,但是我使用的 STL 版本(4.7.2)尚未实现这些功能(请参阅本页的第 30.5 和 30.6.5 点)。

我有机会模仿吗?谢谢

如果你不介意使用 Boost,Boost.Thread 中有 boost::notify_all_at_thread_exit()。

这也可以使用线程局部变量来完成,该变量在析构函数处注册回调。这实际上是函数在libc++中的实现方式。不幸的是,gcc 4.7 还不支持 thread_local 存储类,因此这不起作用。

但是如果我们被允许使用 POSIX 线程函数,那么我们可以将析构函数与 TLS 相关联 pthread_key_create ,这允许我们将函数模拟为:

void notify_all_at_thread_exit(std::condition_variable& cv,
                               std::unique_lock<std::mutex> lock) {
    using Arg = std::tuple<pthread_key_t, 
                           std::condition_variable*, 
                           std::unique_lock<std::mutex>>;
    pthread_key_t key;
    pthread_key_create(&key, [](void* value) {
        std::unique_ptr<Arg> arg (static_cast<Arg*>(value));
        std::get<2>(*arg).unlock();
        std::get<1>(*arg)->notify_all();
        pthread_key_delete(std::get<0>(*arg));
    });
    pthread_setspecific(key, new Arg(key, &cv, std::move(lock)));
}

(这仅针对一个变量进行了优化。您可以更改此设置以注册条件变量堆栈。

相关文章: