# include<iostream>
# include<thread>
# include<vector>
# include<mutex>
# include<condition_variable>
# include<queue>
#include <windows.h>
using namespace std;
//生产者数量
# define PRODUCT_SIZE 20
//消费者数量
# define CUSTOMER_SIZE 1
//最大产品数量
#define MAX_SIZE 10
//互斥锁
mutex mut;
//条件变量
condition_variable con;
//队列,模拟缓冲区
queue<int> que;
//当缓冲区满了,生产者等待,不能继续生产
//当缓冲区空了,消费者等待,不能继续消费
void Producter()
{
static int data = 0;
while (true)
{
Sleep(1000);
std::unique_lock <std::mutex> lck(mut);
while (que.size() > MAX_SIZE)
{
con.wait(lck);// wait for signal 如果满了则等待
}
data %= 20;
que.push(data);
cout <<"线程ID:" <<this_thread::get_id() << "\t生产了产品:" << data << endl;
con.notify_all();//wake up all waiters 如果不满,则唤醒所有等待的线程
data++;
}
}
void Customer()
{
while (true)
{
std::unique_lock <std::mutex> lck(mut);
while (que.empty())
{
con.wait(lck); //如果空了则等待
}
cout << "线程ID:" << this_thread::get_id() << "\t消费了产品:" << que.front() << endl;
que.pop();
con.notify_all(); //如果不空则唤起所有等待的线程
}
}
int main()
{
vector<thread> threadPoll;
//创建生产者和消费者
for (int i = 0; i < PRODUCT_SIZE; ++i)
{
threadPoll.push_back(thread(Producter));
}
for (int i = 0; i < CUSTOMER_SIZE; ++i)
{
threadPoll.push_back(thread(Customer));
}
//21个线程
for (int i = 0; i < PRODUCT_SIZE + CUSTOMER_SIZE; ++i)
{
threadPoll[i].join();
}
return 0;
}
生产者消费者模型
最新推荐文章于 2024-07-22 09:38:37 发布