The core algorithm is the PV operation of the producer process and the consumer process and the rest are simple simulations
#include<cstdio>
#include<Windows.h>
#include<iostream>
#define maxsize 5 //缓冲区大小
typedef int semaphore; //信号量
typedef int production;//物品
semaphore mutex = 1;
semaphore empty = maxsize;
semaphore full = 0;
semaphore buffer[maxsize];//缓冲池数组
static int buffersize = 0;//当前缓冲池元素个数
void producer_Thread(); //生产者进程
void consumer_Thread(); //消费者进程
production produce_item();//生产者生产物品
void consume_item();//消费者消费物品
void put_buffer(production product);//物品存入缓冲区
production remove_buffer();//物品拿出缓冲区
void P(semaphore& x) {
//P操作申请资源 资源数--
x--;
}
void V(semaphore& x) {
//v操作释放资源 资源数++
x++;
}
production produce_item() {
production pro;
std::cout << "生产者已经产生一件物品" << " ";
++buffersize;
std::cout << "当前物品数:" << buffersize << std::endl;
pro = 1;
return pro;
}
void consume_item() {
std::cout << "消费者已经消费一件物品" << " ";
--buffersize;
std::cout << "当前物品数:" << buffersize << std::endl;
}
void producer_Thread() {
while (1) {
Sleep(1000);
P(empty);
P(mutex);
V(mutex);
V(full);
produce_item();
if (full == maxsize) {
consumer_Thread();
}
}
}
void consumer_Thread() {
while (1) {
Sleep(1000);
P(full);
P(mutex);
V(mutex);
V(empty);
consume_item();
if (empty == maxsize)
producer_Thread();
}
}
int main() {
producer_Thread();
return 0;
}