【c++随笔】std::condition_variable及成员函数wait 和 notify_one(以及 notify_all)

std::condition_variable 是 C++ 标准库中的一个类,它允许线程等待某个条件成立(或者说某个事件被触发)。通常与 std::mutex 一起使用,以确保在访问共享数据时线程安全。

std::condition_variable 提供了两个主要的成员函数:wait 和 notify_one(以及 notify_all)。

wait

(std::unique_lock<std::mutex>& lock): 调用此函数时,线程会释放 lock 指向的互斥锁,并进入等待状态,直到另一个线程调用 notify_one 或 notify_all。

notify_one()

唤醒一个等待该 condition_variable 的线程(如果有的话)。

notify_all()

唤醒所有等待该 condition_variable 的线程。一旦线程被唤醒,它会重新获取互斥锁并继续执行。

使用 std::condition_variable 的典型模式如下

cpp
#include <iostream>  
#include <thread>  
#include <mutex>  
#include <condition_variable>  
  
std::mutex mtx;  
std::condition_variable cv;  
bool ready = false;  
  
void print_id(int id) {  
    std::unique_lock<std::mutex> lck(mtx);  
    while (!ready) {  // 如果条件不满足,则等待  
        cv.wait(lck);  // 当前线程被阻塞,当被唤醒且重新获得锁时继续执行  
    }  
    // ... 在这里执行其他操作,比如访问共享数据  
    std::cout << "thread " << id << '\n';  
}  
  
void go() {  
    std::unique_lock<std::mutex> lck(mtx);  
    ready = true;  // 设置条件  
    cv.notify_all();  // 唤醒所有等待的线程  
}  
  
int main() {  
    std::thread threads[10];  
    for (int i = 0; i < 10; ++i) {  
        threads[i] = std::thread(print_id, i);  
    }  
  
    std::cout << "10 threads ready to race...\n";  
    go();  // go!  
  
    for (auto& th : threads) {  
        th.join();  
    }  
  
    return 0;  
}

在上面的示例中,创建了一个 std::condition_variable cv 和一个 std::mutex mtx 来保护一个共享布尔变量 ready。然后创建 10 个线程,每个线程都尝试在 ready 为真时打印其 ID。使用 cv.wait(lck) 来等待 ready 变为真,并使用 go() 函数中的 cv.notify_all() 来唤醒所有等待的线程

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值