以mutex、full、Empty作为信号量
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10; //缓冲区的最尺寸
int in, out; //输入,输出指针
int buf[maxn]; //缓冲区
int mutex; //互斥信号量,1代表临界区内没有进程,0代表应有一个进程进入临界区,-1代表已经有有一个排队的进程
int Empty; //添加Empty信号量
int full; //添加full信号量
int flag; //进程等待队列,1代表没有进程等待,0代表有一个生产者进程等待,-1代表有一个消费者进程等待
/*初始化*/
void init()
{
in = out = 0;
mutex = 1;
flag = 1;
Empty = maxn;
full = 0;
}
/*进程上锁*/
void wait(int *S)
{
(*S)--;
}
/*进程解锁*/
void signal(int *S)
{
(*S)++;
}
/*生产者进程*/
void producer()
{
if (Empty == 0 && full == maxn && in != out) {
cout << "缓冲区已满" << endl;
return ;
}
if (mutex == 0) {
cout << "当前有一个进程已进入临界区,已将其加入等待序列" << endl;
mutex--;
flag = 0;
return ;
}
if (mutex == -1) {
cout << "当前已有一个进程处于等待状态,本次资源申请无效" << endl;
return ;
}
wait(&mutex); //上锁
wait(&Empty);
int production;
cout << "输入一个你要生产的产品:";
cin >> production;
buf[in] = production;
in = (in + 1) % maxn;
cout << "已成功生产一个产品:" << production << endl;
signal(&mutex); //解锁
signal(&full);
}
/*消费者进程*/
void consumer()
{
if (Empty == maxn && full == 0 && in == out) {
cout << "缓冲区为空" << endl;
return ;
}
if (mutex == 0) {
cout << "当前有一个进程已进入临界区,已将其加入等待序列" << endl;
mutex--;
flag = -1;
return ;
}
if (mutex == -1) {
cout << "当前已有一个进程处于等待状态,本次资源申请无效" << endl;
return ;
}
wait(&mutex);
wait(&full);
int i;
i = buf[out];
out = (out + 1) % maxn;
cout << "已消费一个产品:" << i << endl;
signal(&mutex);
signal(&Empty);
}
/*检查进程状态*/
void check()
{
if (flag == 1) return ;
if (flag == 0) {
flag = 1;
producer();
return ;
}
if (flag == -1) {
flag = 1;
consumer();
return ;
}
}
/*显示缓冲区内的元素*/
void print()
{
cout << "缓冲区元素:";
for (int i = out; i < in; i++) cout << buf[i] << " ";
cout << endl;
}
int main()
{
int option;
int Count = 0;
init();
while (1) {
check();
option = rand()%2; //用随机数的方法产生随机进程
if (option == 1) producer();
else consumer();
print();
Count++;
if (Count >= 100) {
cout << "终止" << endl;
break;
}
}
return 0;
}
相应结果: