概述
condition_variable类似于信号量机制,实现了线程的等待和唤醒。
函数接口:
wait() :阻塞等待的同时释放锁(原子操作),还可以添加阻塞判断函数,详见代码
notify_all() : 唤醒所有阻塞等待的线程
notify_one(): 唤醒某一个等待的线程
代码
#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<chrono>
using namespace std;
mutex m;
condition_variable cond;
int LOOP = 10;
int flag = 0;
void fun(int id) {
for (int i = 0; i < LOOP; i++) {
unique_lock<mutex> lk(m); //加锁
//写法1,while循环比较,多次唤醒时,只要不满足条件就阻塞,if只判断一次会出错
/*while (id != flag)
cond.wait(lk);*/
//写法2,实现原理和上面一样 ,id != flag时会阻塞,唤醒时继续判断,id == flag才会唤醒成功
cond.wait(lk, [=]() {
return id == flag;
});
cout << (char)('A' + id) << " ";
flag = (flag + 1) % 3;
cond.notify_all();
}
}
int main() {
thread A(fun, 0);
thread B(fun, 1);
thread C(fun, 2);
A.join();
B.join();
C.join();
cout << endl;
cout << "main end" << endl;
return 0;
}
测试结果:
semaphore源码
#pragma once
#include<mutex>
#include<condition_variable>
class semaphore {
public:
semaphore(long count = 0) :count(count) {}
void wait() {
std::unique_lock<std::mutex>lock(mx);
cond.wait(lock, [&]() {return count > 0; });
--count;
}
void signal() {
std::unique_lock<std::mutex>lock(mx);
++count;
cond.notify_one();
}
private:
std::mutex mx;
std::condition_variable cond;
long count;
};