notify_one与notify_all

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
notify_allnotify_one 都是 C++ 中的条件变量(condition variable)的成员函数,用于唤醒等待线程。 下面是一个简单的使用实例: ``` #include <iostream> #include <thread> #include <mutex> #include <condition_variable> std::mutex mtx; std::condition_variable cv; bool ready = false; void worker(int id) { std::unique_lock<std::mutex> lock(mtx); while (!ready) { std::cout << "Worker " << id << " is waiting..." << std::endl; cv.wait(lock); } std::cout << "Worker " << id << " is working..." << std::endl; } void notifier() { std::unique_lock<std::mutex> lock(mtx); ready = true; cv.notify_all(); } int main() { std::thread t1(worker, 1); std::thread t2(worker, 2); std::thread t3(worker, 3); std::this_thread::sleep_for(std::chrono::seconds(1)); std::thread t4(notifier); t1.join(); t2.join(); t3.join(); t4.join(); return 0; } ``` 上面的代码创建了三个 worker 线程和一个 notifier 线程。worker 线程会等待 ready 变量为 true,notifier 线程会将 ready 变量设置为 true,并通过 notify_all 函数唤醒所有等待线程。 运行上面的代码,输出结果如下: ``` Worker 1 is waiting... Worker 2 is waiting... Worker 3 is waiting... Worker 3 is working... Worker 2 is working... Worker 1 is working... ``` 可以看到,三个 worker 线程都等待在条件变量上,直到 notifier 线程唤醒它们,并且它们同时开始工作。如果将 notify_all 改为 notify_one,那么只会唤醒一个等待线程,输出结果会有所不同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gaopeng@step by step

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值