汉森实现管程的实例

一、管程来解决生产者/消费者问题
1)
[objc] view plain copy 在CODE上查看代码片派生到我的代码片
Struct Monitor
{
condition NF,NE;
int Buffer[n];
int k = 0,t = 0,count = 0;
define Add(int),Remove(int);
use wait(),signal(),check(),release();
void init() //初始化局部变量和条件变量
{
count = 0;k = 0;t = 0;NF = 0;NE = 0;
}
vodi Add(int i)
{
check();
if(count ==n) wait(NF);
Buffer[k] = i;
k = (k+1)%n;
count++;
signal(NE);
release();
}
void Remove(int &i)
{
check();
if(count == 0)wait(NE);
i = Buffer[t];
t = (t+1)%n;
count–;
signal(NF);
release();
}
}

[objc] view plain copy 在CODE上查看代码片派生到我的代码片
process producteri()//i = 1,2…,m
{
int x;
x = 生产一个产品(整数)
Add(x);
}

process consumerj()//j = 1,2,…,r
{
int x;
Remove(x);
消费该产品(整数);
}

二、用管程来解决优先写着的读者/写着问题
优先写者的读者/写着问题要求是:
①读者共享;
②写着互斥;
③有读者在读,写着不可写;
④写着在写,读者不可读;
⑤当读者在读时,写着提出写的要求,后面的读者就不允许进入读文件;
⑥当里面的读者读完时,由写着进入写;
⑦当写着写完后,优先唤醒等待的写着,如果没有写着等待,才唤醒等待的读者进行读;

1)
[objc] view plain copy 在CODE上查看代码片派生到我的代码片
struct Monitor
{
condition RR,WW;
int ReaderCnt,WriterCnt;
define StartRead,EndRead,StartWrite,EndWrite;
use wait,signal,check,release;
void StartRead()
{
check();
if(WriterCnt>0)wait(RR);
ReaderCnt++;
signal(RR);
release();
}
void EndRead()
{
check();
ReaderCnt–;
if(ReaderCnt == 0)signal(WW);
release();
}
void StartWrite()
{
check();
WriterCnt++;
if(ReadCnt>0 || WriterCnt>1)wait(WW);
release();
}
void EndWrite()
{
check();
WriterCnt–;
if(WriterCnt>0)signal(WW);
else
signal(RR);
release();
}
void init()
{
ReaderCnt=0;WriterCnt=0;RR=0;WW=0;
}
}

[objc] view plain copy 在CODE上查看代码片派生到我的代码片
process reader()
{
ReadWriter.StartRead();
读文件;
ReadWriter.EndRead();
}

process writer()
{
ReadWriter.StartWrite();
写文件;
ReadWriter.EndWrite();
}

你可能感兴趣的:(管程)