#include<iostream>
#include<stack>
#include<string>
#include<malloc.h>
#include<thread>
#include<mutex>
using namespace std;
//互斥锁
mutex m;
//定义一个栈来存放需要消费的数据
stack<int> s;
//生产者线程
void producer(){
while(1){
//让这个线程沉睡一会再生产一个产品
this_thread::sleep_for(chrono::seconds(3));
//根据时间获取产品id
int id = time(NULL);
//加锁
m.lock();
cout << "I am the producer, I have made the NO." << id << " product." << endl;
//将产品压入栈
s.push(id);
//解锁
m.unlock();
}
}
//消费者线程
void customer(){
while(1){
//加锁
m.lock();
if(!s.empty()){
//从栈中取出产品
int tmp = s.top();
cout << "I am the customer, I have take take the NO." << tmp <<" product." << endl;
s.pop();
}
else{
cout << "There are no product" << endl;
}
//解锁
m.unlock();
}
}
int main(){
//新建两个线程,执行生产者和消费者函数
thread pthread(producer);
thread cthread(customer);
//等待两个线程直结束
pthread.join();
cthread.join();
return 0;
}
消费者生产者模式
最新推荐文章于 2024-05-19 22:20:48 发布