问题描述:
一组生产者进程和一组消费者进程共享一个大小为n的缓冲区,只有没其他进程使用缓冲区时,其中的一个进程才能访问缓冲区。对于消费者来说,只有缓冲区不空时才能访问缓冲区并读取信息;对于生产者来说,只有缓冲区不满是才能访问缓冲区并写入信息。
#include <iostream>
#include <stdlib.h>
using namespace std;
const int n = 10;//设置缓冲区数量
//信号量数据结构
typedef struct semaphore {
int mutex;//互斥信号
int empty;//空缓冲区数量
int full; //满缓冲区数量
}*semaphoreptr;
//缓冲区数组
int a[n];
//定义进程类
class Progress {
char name;
public:
Progress() {}
~Progress(){}
virtual void wait(semaphoreptr s,int a[]) = 0;//申请访问缓冲区
virtual void signal(semaphoreptr s) = 0;//使用完毕,释放缓冲区
};
class Producer:public Progress {
public:
void wait(semaphoreptr s,int a[]);
void signal(semaphoreptr s);
};
void Producer::wait(semaphoreptr s,int a[]) {
if (s->mutex == 1) {
//此时表示消费者正在读取缓冲区信息
cout << "有进程正在占用缓冲区,无法进行写入..." << endl;
return;
}
if (s->full == n + 1) {
cout << "缓冲区以满,无法进行写入..." << endl;
return;
}
s->mutex = 1;//锁住缓冲区
a[s->full] = 6;//默认输入数字为6
}
void Producer::signal(semaphoreptr s) {
if (s->mutex == 1) {
s->mutex = 0;//打开缓冲区的互斥锁
s->full++;
s->empty--;
cout << "数据输入成功,释放缓冲区使用权..." << endl;
}
}
class Consumer :public Progress {
public:
void wait(semaphoreptr s, int a[]);
void signal(semaphoreptr s);
};
void Consumer::wait(semaphoreptr s, int a[]) {
if (s->mutex == 1) {
cout << "有进程占用缓冲区,无法进行读操作..." << endl;
return;
}
if (s->empty == n) {
cout << "缓冲区为空,无法进行读操作..." << endl;
return;
}
s->mutex = 1;
s->full--;
}
void Consumer::signal(semaphoreptr s) {
if (s->mutex == 1) {
s->mutex = 0;
s->empty++;
cout << "读取成功,读出的数为" << a[s->full] << " 释放缓冲区使用权..."<<endl;
}
}
int main()
{
semaphoreptr s = (semaphore *)malloc(sizeof(semaphore));
s->mutex = 0;
s->empty = n;
s->full = 0;
Producer p;
Consumer c;
p.wait(s, a);
p.signal(s);
c.wait(s, a);
c.signal(s);
p.wait(s, a);
c.wait(s, a);
p.signal(s);
c.wait(s, a);
c.signal(s);
return 0;
}
参考书籍: 王道 《2018年操作系统考研复习指导》