如何在线程退出时触发代码,而不使用函数 *_at_thread_exit
How to trigger code when a thread exits, without using functions *_at_thread_exit?
假设我的应用程序中有两个线程,我需要在另一个线程退出时通知我的主线程。
我知道 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)));
}
(这仅针对一个变量进行了优化。您可以更改此设置以注册条件变量堆栈。
相关文章:
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- 将模板(没有规范)传递给 std::thread() 会出现错误:<未解析的重载函数类型>匹配错误
- 在没有复制构造函数的对象的成员函数中启动 std::thread
- 无法将参数传递给 boost::thread 构造函数
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- 如何在 UWP C++/CX 中对象的成员函数中使用 std::thread
- 使用 std::thread & std::bind 在成员函数中启动线程
- 错误:调用 std::thread 没有匹配函数
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- std::thread从函数启动,无需等待线程完成
- 使用 boost::thread 运行函子,但析构函数被错误地调用
- 睡眠影响 std::thread 调用哪个虚拟成员函数?
- 如何在不接触函数本身的情况下暂停和恢复 C++11 std::thread 的功能
- C++ - 在 std::thread 中调用重载函数时编译失败
- 子类化 std::thread:构造器中可变参数模板函数的问题
- 如果容器不是调用函数中的引用,则使用 std::thread 传递对迭代器的引用将失败
- 标准库中是否有与 std::thread 的构造函数语义匹配的类型擦除函数包装器?
- 将回调函数中对对象的引用传递给 std::thread
- thread.detach() 函数的左值何时会超出以下代码的范围
- VSCod 中的C++:错误:没有用于初始化'std::thread'的匹配构造函数