首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::notify_all_at_thread_exit

Defined in header <condition_variable>

?

?

void notify_all_at_thread_exit( std::condition_variable& cond, std::unique_lock<std::mutex> lk );

?

(since C++11)

notify_all_at_thread_exit提供一种机制,通知其他线程给定线程已完全完成,包括销毁所有线程。螺纹[医]局部物品。它的运作如下:

  • 先前获得的锁的所有权lk转移到内部存储。
  • 执行环境被修改,以便当当前线程退出时,条件变量。cond通知如下:

lk.unlock(); cond.notify_all();

暗含lk.unlock后序中定义的28名ASstd::memory_order%29销毁所有物体线程本地存储持续时间与当前线程关联。

所提供的设施可达到同等效果。std::promisestd::packaged_task...

注记

调用此函数如果lock.mutex()不被当前线程锁定是未定义的行为。

调用此函数如果lock.mutex()与当前正在等待相同条件变量的所有其他线程使用的互斥对象不同,这是未定义的行为。

提供的锁lk直到线程退出为止。一旦调用了此函数,就不会再有线程获得相同的锁以等待cond如果某个线程正在此条件变量上等待,则当锁被伪造唤醒时,它不应试图释放和重新获取锁。

在典型的用例中,这个函数是分离线程调用的最后一个函数。

参数

cond

-

the condition variable to notify at thread exit

lk

-

the lock associated with the condition variable cond

返回值

%280%29

这个部分代码片段说明了如何notify_all_at_thread_exit可用于避免访问依赖于线程局部变量的数据,而这些线程局部变量正在被销毁:

二次

代码语言:javascript
复制
#include <mutex>
#include <thread>
#include <condition_variable>
 
std::mutex m;
std::condition_variable cv;
 
bool ready = false;
ComplexType result;  // some arbitrary type
 
void thread_func()
{
    std::unique_lock<std::mutex> lk(m);
    // assign a value to result using thread_local data
    result = function_that_uses_thread_locals();
    ready = true;
    std::notify_all_at_thread_exit(cv, std::move(lk));
} // 1. destroy thread_locals, 2. unlock mutex, 3. notify cv
 
int main()
{
    std::thread t(thread_func);
    t.detach();
 
    // do other work
    // ...
 
    // wait for the detached thread
    std::unique_lock<std::mutex> lk(m);
    while(!ready) {
        cv.wait(lk);
    }
    process(result); // result is ready and thread_local destructors have finished
}

二次

另见

set_value_at_thread_exit

sets the result to specific value while delivering the notification only at thread exit (public member function of std::promise)

make_ready_at_thread_exit

executes the function ensuring that the result is ready only once the current thread exits (public member function of std::packaged_task)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com