C++11条件变量:wait(lock),notify_one()与notify_all()

15 篇文章 1 订阅
文章详细解释了C++中std::condition_variable的notify_one()和notify_all()函数在多线程编程中的作用。notify_one()只会唤醒等待队列的第一个线程,该线程能立即获得锁并执行。而notify_all()则唤醒所有等待线程,它们会竞争锁,只有一个能成功。被唤醒但未获取到锁的线程会持续尝试获取锁,而不是再次阻塞。示例代码展示了这两个函数的不同效果。
摘要由CSDN通过智能技术生成

notify_one()与notify_all()常用来唤醒阻塞的线程。

notify_one():因为只唤醒等待队列中的第一个线程;不存在锁争用,所以能够立即获得锁。其余的线程不会被唤醒,需要等待再次调用notify_one()或者notify_all()。

notify_all():会唤醒所有等待队列中阻塞的线程,存在锁争用,只有一个线程能够获得锁。那其余未获取锁的线程接着会怎么样?会阻塞?还是继续尝试获得锁?

答案是会继续尝试获得锁(类似于轮询),而不会再次阻塞。当持有锁的线程释放锁时,这些线程中的一个会获得锁。而其余的会接着尝试获得锁。

// condition_variable example
#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
 
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
 
void task_id(int id) {
    std::unique_lock<std::mutex> lck(mtx);
    while (!ready) cv.wait(lck);
    // ...
    std::cout << "thread " << id << '\n';
}
 
void notify() {
    std::unique_lock<std::mutex> lck(mtx);
    ready = true;
    cv.notify_all(); // 这是重点
}
 
int main()
{
    std::thread threads[10];
    // spawn 10 threads:
    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(task_id, i);
 
    std::cout << "10 threads ready to race...\n";
    notify();                       // notify!
 
    for (auto& th : threads) th.join();
 
    return 0;
}

运行结果为:

10 threads ready to race...

thread 2

thread 0

thread 9

thread 4

thread 6

thread 8

thread 7

thread 5

thread 3

thread 1

输出表明所有线程被唤醒,然后依旧获得了锁。

如果将go()中的cv.notify_all()改为cv.notify_one(),运行结果为:

10 threads ready to race...

thread 0

输出表明只有有一个线程被唤醒,然后该线程释放锁,这时锁已经处理非锁定状态,但是其余线程依旧处于阻塞状态。

所以,线程阻塞在condition_variable时,它是等待notify_one()或者notify_all()来唤醒。

线程被唤醒后,会通过轮询方式获得锁,获得锁前也一直处理运行状态,不会被再次阻塞。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值