condition_variable 条件变量

条件变量

条件变量是允许多个线程相互交流的同步原语。它允许一定量的线程等待(可以定时)另一线程的提醒,然后再继续。条件变量始终关联到一个互斥。


头文件

<condition_variable>


condition_variable

condition_variable 类是同步原语,能用于阻塞一个线程,或同时阻塞多个线程,直至另一线程修改共享变量(条件)并通知 condition_variable 。

有意修改变量的线程必须(通知线程)

  1. 获得 std::mutex (典型地通过 std::lock_guard )
  2. 在保有锁时进行修改
  3. 在 std::condition_variable 上执行 notify_one 或 notify_all (不需要为通知保有锁)

即使共享变量是原子的,也必须在互斥下修改它,以正确地发布修改到等待的线程。

任何有意在 std::condition_variable 上等待的线程必须(等待线程)

  1. 获得 std::unique_lock<std::mutex> ,在与用于保护共享变量者相同的互斥上
  2. 执行 wait 、 wait_for 或 wait_until ,等待操作自动释放互斥,并悬挂线程的执行。
  3. condition_variable 被通知时,时限消失或虚假唤醒发生,线程被唤醒,且自动重获得互斥。之后线程应检查条件,若唤醒是虚假的,则继续等待。

std::condition_variable 只可与 std::unique_lock<std::mutex> 一同使用;此限制在一些平台上允许最大效率。 std::condition_variable_any 提供可与任何基础可锁 (BasicLockable) 对象,例如 std::shared_lock 一同使用的条件变量。

condition_variable 容许 wait 、 wait_for 、 wait_until 、 notify_one 及 notify_all 成员函数的同时调用。

类 std::condition_variable 是标准布局类型 (StandardLayoutType) 。它不可复制构造 (CopyConstructible) 、可移动构造 (MoveConstructible) 、可复制赋值 (CopyAssignable) 或可移动赋值 (MoveAssignable) 。


公共方法

名称描述
notify_one通知一个等待的线程
notify_all通知所有等待的线程
wait阻塞当前线程,直到条件变量被唤醒
wait_for阻塞当前线程,直到条件变量被唤醒,或到指定时限时长后
wait_until阻塞当前线程,直到条件变量被唤醒,或直到抵达指定时间点
native_handle返回原生句柄

wait


wait(_Lck)
流程图

在这里插入图片描述


示例
#include <iostream>
#include <condition_variable>

using namespace std;

mutex wait_mutex;
condition_variable wait_condition_variable;

// 等待线程函数
void wait_thread_func()
{
	unique_lock<mutex> lock(wait_mutex);
	cout << "等待线程(" << this_thread::get_id() << "): 开始等待通知..." << endl;
	wait_condition_variable.wait(lock);
	cout << "等待线程(" << this_thread::get_id() << "): 继续执行代码..." << endl;
}

int main()
{
	thread wait_thread(wait_thread_func);

	this_thread::sleep_for(1s); // 等待1秒后进行通知
	cout << "通知线程(" << this_thread::get_id() << "): 开始通知等待线程..." << endl;
	wait_condition_variable.notify_one();
	wait_thread.join();
	cout << "--- main结束 ---" << endl;
}
Output
等待线程(12348): 开始等待通知…
通知线程(15856): 开始通知等待线程…
等待线程(12348): 继续执行代码…
— main结束 —

错误示例:等待前通知,导致无法获得通知
#include <iostream>
#include <condition_variable>

using namespace std;

mutex wait_mutex;
condition_variable wait_condition_variable;

// 等待线程函数
void wait_thread_func()
{
    this_thread::sleep_for(1s); // 等待1秒后再等待通知
    
	unique_lock<mutex> lock(wait_mutex);
	cout << "等待线程(" << this_thread::get_id() << "): 开始等待通知..." << endl;
	wait_condition_variable.wait(lock);
	cout << "等待线程(" << this_thread::get_id() << "): 继续执行代码..." << endl;
}

int main()
{
	thread wait_thread(wait_thread_func);
	cout << "通知线程(" << this_thread::get_id() << "): 开始通知等待线程..." << endl;
	wait_condition_variable.notify_one();
	wait_thread.join();
	cout << "--- main结束 ---" << endl;
}
Output
通知线程(21892): 开始通知等待线程…
等待线程(2120): 开始等待通知…
(无限等待…)

wait(_Lck, _Pred)
流程图

在这里插入图片描述


示例:等待后通知
using namespace std;

mutex wait_mutex;
condition_variable wait_condition_variable;
bool ready = false;

// 等待线程函数
void wait_thread_func()
{
	// 等待通知再继续执行
	unique_lock<mutex> lock(wait_mutex);
	cout << "等待线程(" << this_thread::get_id() << "): 开始等待通知..." << endl;
	wait_condition_variable.wait(lock, [] { return ready; });
	cout << "等待线程(" << this_thread::get_id() << "): 继续执行代码..." << endl;
}

int main()
{
	thread wait_thread(wait_thread_func);

    this_thread::sleep_for(1s); // 等待1秒
	unique_lock<mutex> lock(wait_mutex);
	cout << "通知线程(" << this_thread::get_id() << "): 开始通知等待线程..." << endl;
	ready = true;
	lock.unlock(); // 不解锁的话,等待线程无法获得锁,则会进入死锁
	wait_condition_variable.notify_one();

	wait_thread.join();
	cout << "--- main结束 ---" << endl;
}
Output
等待线程(18172): 开始等待通知…
通知线程(19740): 开始通知等待线程…
等待线程(18172): 继续执行代码…
— main结束 —

示例:等待前通知
using namespace std;

mutex wait_mutex;
condition_variable wait_condition_variable;
bool ready = false;

// 等待线程函数
void wait_thread_func()
{
    this_thread::sleep_for(1s); // 等待1秒
    
	// 等待通知再继续执行
	unique_lock<mutex> lock(wait_mutex);
	cout << "等待线程(" << this_thread::get_id() << "): 开始等待通知..." << endl;
	wait_condition_variable.wait(lock, [] { return ready; });
	cout << "等待线程(" << this_thread::get_id() << "): 继续执行代码..." << endl;
}

int main()
{
	thread wait_thread(wait_thread_func);

	unique_lock<mutex> lock(wait_mutex);
	cout << "通知线程(" << this_thread::get_id() << "): 开始通知等待线程..." << endl;
	ready = true;
	lock.unlock(); // 不解锁的话,等待线程无法获得锁,则会进入死锁
	wait_condition_variable.notify_one();

	wait_thread.join();
	cout << "--- main结束 ---" << endl;
}
Output
通知线程(10972): 开始通知等待线程…
等待线程(22632): 开始等待通知…
等待线程(22632): 继续执行代码…
— main结束 —

错误示例:通知线程不加lock可能出现的问题
#include <iostream>
#include <condition_variable>

using namespace std;

mutex wait_mutex;
condition_variable wait_condition_variable;
bool ready = false;

// 等待线程函数
void wait_thread_func()
{
	// 等待通知再继续执行
	unique_lock<mutex> lock(wait_mutex);
	cout << "等待线程(" << this_thread::get_id() << "): 开始等待通知..." << endl;
	wait_condition_variable.wait(lock, []
		{
			bool state = ready;
			cout << "wait执行中(判断条件后,等待通知前)" << endl; // 模拟“wait执行中”
			this_thread::sleep_for(3s);
			return state;
		});
	cout << "等待线程(" << this_thread::get_id() << "): 继续执行代码..." << endl;
}

int main()
{
	thread wait_thread(wait_thread_func);

	this_thread::sleep_for(1s); // 模拟“wait执行中”进行通知

	//unique_lock<mutex> lock(wait_mutex);
	cout << "通知线程(" << this_thread::get_id() << "): 开始通知等待线程..." << endl;
	ready = true;
	//lock.unlock(); // 不解锁的话,等待线程无法获得锁,则会进入死锁
	wait_condition_variable.notify_one();

	wait_thread.join();
	cout << "--- main结束 ---" << endl;
}
Output
等待线程(19732): 开始等待通知…
wait执行中(判断条件后,等待通知前)
通知线程(6408): 开始通知等待线程…
(无限等待…)
解决方案:加入lock
#include <iostream>
#include <condition_variable>

using namespace std;

mutex wait_mutex;
condition_variable wait_condition_variable;
bool ready = false;

// 等待线程函数
void wait_thread_func()
{
	// 等待通知再继续执行
	unique_lock<mutex> lock(wait_mutex);
	cout << "等待线程(" << this_thread::get_id() << "): 开始等待通知..." << endl;
	wait_condition_variable.wait(lock, []
		{
			bool state = ready;
			cout << "wait执行中(判断条件后,等待通知前)" << endl; // 模拟“wait执行中”
			this_thread::sleep_for(3s);
			return state;
		});
	cout << "等待线程(" << this_thread::get_id() << "): 继续执行代码..." << endl;
}

int main()
{
	thread wait_thread(wait_thread_func);

	this_thread::sleep_for(1s); // 模拟“wait执行中”进行通知

	unique_lock<mutex> lock(wait_mutex);
	cout << "通知线程(" << this_thread::get_id() << "): 开始通知等待线程..." << endl;
	ready = true;
	lock.unlock(); // 不解锁的话,等待线程无法获得锁,则会进入死锁
	wait_condition_variable.notify_one();

	wait_thread.join();
	cout << "--- main结束 ---" << endl;
}
Output
等待线程(18072): 开始等待通知…
wait执行中(判断条件后,等待通知前)
通知线程(15672): 开始通知等待线程…
wait执行中(判断条件后,等待通知前)
等待线程(18072): 继续执行代码…
— main结束 —
总结

拥有lock:

只会在 “wait执行前/后” 进行通知

(通知后"等待线程"可以继续执行)

没有lock:

假如在 “wait执行中(判断条件后,等待通知前)” 进行通知,判断条件为false,并且无法受到通知(造成此次通知无效, “等待线程” 依然处于等待通知状态)


相关参考

微软文档(condition-variable)

cppreference(condition-variable)

  • 10
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值