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;
}