![](https://img2020.cnblogs.com/blog/1975550/202107/1975550-20210715142450208-943196383.png)
操作系统——使用线程实现生产者消费者问题。 生产者生产物品用于消费者消费。生产者生产的商品只可以保存2个。生产者生产5次,消费者全部消费。消费者5次消费后死亡,生产者检测到消费者死亡后跟随死亡,并清空所有产品。(包含程序框图)
操作系统——使用线程实现生产者消费者问题。 生产者生产物品用于消费者消费。生产者生产的商品只可以保存2个。生产者生产5次,消费者全部消费。消费者5次消费后死亡,生产者检测到消费者死亡后跟随死亡,并清空所有产品。(包含程序框图)
实验结果
Linux效果图(采用UOS + VScode + g++)
![image](https://img2020.cnblogs.com/blog/1975550/202107/1975550-20210715142450208-943196383.png)
程序框图
![image](https://img2020.cnblogs.com/blog/1975550/202107/1975550-20210715142555855-1200001010.png)
C++代码:
#include<unistd.h>
#include<semaphore.h>
#include<pthread.h>
#include<iostream>
using namespace std;
#define PRODUCER 1//生产者数量
#define CONSUMER 1//消费者数量
#define BUFFER 2//缓冲区数量
sem_t empty_sem,full;
//同步信号量
pthread_mutex_t mutex;
//互斥信号量
int buffer[2];
//缓冲区
int index_in=0,index_out=0;
//生产者 消费者 存放消费的位置
int sum=3;
int m;
int i=0;
void *Producer(void *)//生产者函数 {
sleep(1);
while(1) {
sem_wait(&empty_sem);
pthread_mutex_lock(&mutex);
m=rand();
buffer[index_in]=m;
cout<<"生产 "<<"商品内容:"<<m<<endl;
index_in=(index_in+1)%BUFFER;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
return 0;
}
void *Consumer(void *)//消费者函数 {
int i=0;
while(i<5) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
m=buffer[index_out];
cout<<"第"<<++i<<"次消费 "<<"商品内容:"<<m<<endl;
index_out=(index_out+1)%BUFFER;
pthread_mutex_unlock(&mutex);
sem_post(&empty_sem);
}
return 0;
}
int main() {
int sinit1=sem_init(&empty_sem,0,BUFFER);
//初始化同步信号量
int sinit2=sem_init(&full,0,0);
int minit=pthread_mutex_init(&mutex,NULL);
//初始化互斥信号量
int tmp1, tmp2;
pthread_t thread1, thread2;
int producer, consumer;
producer = pthread_create(&thread1, NULL, Producer, NULL);
if (producer!= 0)
cout<<"生产线程 创建失败"<<endl; else
cout<<"生产线程 创建成功"<<endl;
consumer = pthread_create(&thread2, NULL,Consumer, NULL);
if (consumer!= 0)
cout<<"消费线程 创建失败"<<endl; else
cout<<"消费线程 创建成功"<<endl;
tmp2 = pthread_join(thread2, NULL);
cout<<"消费结束"<<endl;
tmp1 = pthread_join(thread2, NULL);
buffer[2]= {
NULL
}
;
cout<<"生产结束"<<endl;
return 0;
}
//g++ test6.cpp -o test6 -lpthread&&./test6