条件变量的wait操作:先释放互斥锁,将其放入互斥变量的等待队列中,等待其他线程唤醒,再放入互斥锁的等待队列中去获得锁进行操作。
cpp
#include<iostream>
#include<condition_variable>
#include<mutex>
#include<thread>
#include<queue>
using namespace std;
queue<int>sq;
const int maxsize = 30;
condition_variable notempty;
condition_variable notfull;
mutex m;
int sumsize = 0;
void Producer()
{
while (1)
{
std::unique_lock<mutex>lock(m);
while (sumsize>=maxsize)
{
notfull.wait(lock); //等待不为满,才可以进行生产
//
}
sq.push(rand());
sumsize++;
cout << "Producer " << sq.front() << endl;
notempty.notify_all();
}
}
void Consumer()
{
while (1)
{
std::unique_lock<mutex>lock(m);
while (sumsize == 0)
{
notempty.wait(lock); //等待不为空 才可以进行消费
}
int tmp = sq.front();
sq.pop();
sumsize--;
cout << "Consumer " << tmp<< endl;
notfull.notify_all();
}
}
int main()
{
thread th1(Producer); //开启两个线程
thread th2(Consumer); //开启线程
th1.join();
th2.join();
return 0;
}