生产者与消费者

以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;
}

 

相应结果:

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水能zai舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值