std::condition_variable的notify_one()
mob 发布于 2022-02-28

std::condition_variable的notify_one()方法,对于多个监听线程,具体触发哪个是随机的,如下面代码

#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>

std::condition_variable cv;
std::mutex cv_m;
int i = 0;

void waits(int param)
{
	std::unique_lock<std::mutex> lk(cv_m);
	std::cerr << "Waiting... \n";
	cv.wait(lk, []() {return i == 1; });
	std::cerr << param;
	std::cerr << "...finished waiting. i == 1\n";
}

void signals()
{
	std::this_thread::sleep_for(std::chrono::seconds(1));
	std::cerr << "Notifying...\n";
	cv.notify_all();
	std::this_thread::sleep_for(std::chrono::seconds(1));
	i = 1;
	std::cerr << "Notifying again...\n";
	//cv.notify_all();
	cv.notify_one();
}

int main()
{
	std::thread t1(waits,1), t2(waits,2), t3(waits,3), t4(signals);
	t1.join(); t2.join(), t3.join(), t4.join();
	system("pause");
}

第一次运行输出如下,可以看到是t2线程响应

Waiting...

Waiting...

Waiting...

Notifying...

Notifying again...

2...finished waiting. i == 1

第二次运行结果如下,t1线程响应

Waiting...

Waiting...

Waiting...

Notifying...

Notifying again...

1...finished waiting. i == 1

 

mob
关注 私信
文章
66
关注
0
粉丝
0