notify_one() 与 notify_all() 的区别
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();
}
{
std::thread threads[];
( i = ; i < ; ++i)
threads[i] = std::(task_id, i);
std::cout << ;
();
(& th : threads)
th.();
;
}

