#include <mutex>
#include <condition_variable>
#include <deque>
#include <iostream>
using namespace std;
// 定义两个条件变量
// 队列未满
std::condition_variable QueueNotFull;
// 队列不空
std::condition_variable QueueNotEmpty;
// 队列锁
std::mutex QueueMutex;
// 队列
std::deque<int> Que;
enum
{
// 队列的最大容量
MaxSize = 16
};
// 判断队列是否为空
bool Empty()
{
return Que.empty();
}
// 判断队列是否已满
bool Full()
{
return Que.size() == MaxSize;
}
// 往队列中添加数据
void Put(int element)
{
// 加锁
std::unique_lock<std::mutex> locker(QueueMutex);
// 如果队列已经满了,那么等待
while (Full())
{
cout << "Full !! Wait !!" << endl;
QueueNotFull.wait(locker);
}
Que.push_back(element);
// 通知其他线程,队列不空
QueueNotEmpty.notify_all();
}
// 从队列中取出数据
int Get()
{
// 加锁
std::unique_lock<std::mutex> locker(QueueMutex);
// 如果队列为空,那么等待
while (Empty())
{
cout << "Empty!! Wait!!" << endl;
QueueNotEmpty.wait(locker);
}
int t = Que.front();
Que.pop_front();
// 通知其他等待的对象,队列不满
QueueNotFull.notify_all();
return t;
}
// 消费者线程
void GetFunc()
{
while (1)
{
int var;
var = Get();
cout << "Get : " << var << endl;
}
}
// 生产者线程
void PutFunc()
{
srand((unsigned int)time(0));
while (1)
{
int var = rand()%100;
Put(var);
}
}
int main(int arc,char** argv)
{
// 启动两个线程
std::thread td1(GetFunc);
std::thread td2(PutFunc);
td1.join();
td2.join();
return 0;
}