Day 4 线程的等待与唤醒

condition_variable:一个条件变量(类),在头文件<mutex>中。

该类有三个方法,wait(), notify_one(),notify_all()。

wait()原型:wait(unique_lock<mutex>& _Lck, _Predicate _Pred),第一个参数是一个unique_lock<mutex>类型的,绑定某个互斥量(注意,这个必须先上锁),第二个参数是个谓词。

作用:当线程执行到wait时,会先判断第二个谓词返回的是true还是false。如果是true,那就无事发生;如果是false,就会将该进程堵塞,然后将互斥量的锁给打开,直到有其他线程执行notify_one或者notify_all时才会先给wait绑定的互斥量加锁,再继续判断谓词,直到返回true或者继续堵塞。

用法:

class A {
private:
	mutex mymutex;
	condition_variable mycond;
	int i = 3;

public:
	void hanshu1() {
		unique_lock<mutex> lock1(mymutex);         //要先用unique_lock上锁哦
		mycond.wait(lock1, [this]()->bool {     
			if (i == 0) { return true; }             //这是用lambda表达式做谓词
			else { i--; return false; }
			}
		);
	}
};

notify_one/notify_all:用于唤醒进入等待的线程,其中notify_one调用一次只能唤醒一个进入等待的线程(会唤醒第一个进入等待的线程而不是随机唤醒);notify_all会唤醒所有进入等待的线程。

用法如下:

class A {
private:
	mutex mymutex;
	condition_variable mycond;
	int i = 5;

public:
	void hanshu2() {
		int i = 20;
		while (i--) {
			Sleep(1);          //个人测试时使用,等待一毫秒便于另一线程获取锁
			unique_lock<mutex> lock1(mymutex);
			//mycond.notify_one();
			mycond.notify_all();
		}
	}
};

总代码如下:

#include<iostream>
#include<mutex>
#include<thread>
#include<Windows.h>
using namespace std;

class A {
private:
	mutex mymutex;
	condition_variable mycond;
	int i = 5;

public:
	void hanshu1() {

		unique_lock<mutex> lock1(mymutex);
		mycond.wait(lock1, [this]()->bool {
			cout << "唤醒函数1" << endl;
			if (i == 0) { return true; }
			else { i--; cout << "函数1等待" << endl; return false; }
			}
		);
		
		cout << "函数1被解锁啦" << endl;
	}
	void hanshu2() {
		int i = 20;
		while (i--) {
			Sleep(1);
			unique_lock<mutex> lock1(mymutex);
			cout << "11111" << endl;
			//mycond.notify_one();
			mycond.notify_all();
		}
	}
	void hanshu3() {
		int i = 5;
		unique_lock<mutex> lock1(mymutex);
		mycond.wait(lock1, [&i]()->bool {
			cout << "唤醒函数3" << endl;
			if (i == 0) { return true; }
			else { i--; cout << "函数3等待" << endl; return false; }
			}
		);

		cout << "函数3被解锁啦" << endl;
	}
};

int main() {
	A a;
	thread mythread1(&A::hanshu1, &a);
	thread mythread3(&A::hanshu3, &a);
	thread mythread2(&A::hanshu2, &a);
	mythread1.join();
	mythread2.join();
	mythread3.join();

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值