管程机制--解决生产者消费者问题
生产者消费者问题是比较经典的问题。
管程机制的好处在于所有的进程都采用这种机制获取临界资源,不需要考虑怎么解决临界资源内在的冲突,只需要调用管程提供的函数方法就好。
来看下代码实现:
管程定义:
moniter procuder_conmuser() {
int in,out,count;
Item[] buffer[n]; //缓冲池的长度。
Condition notnull,notempty; //条件变量
Entry put(item) {
if(count>=n) notfull.wait();
buffer[in]=nextp;
in=(in+1)%n;
count++;
notempty.signal();
}
Entry get(item) {
if(count==0) notempty.wait();
nextp=buffer[out];
out=(out+1)%n;
count--;
notfull.signal();
}
{
in=out=0;
count=0; //初始化管程的局部变量
}
}
生产者消费者进程:
void producer(int i) {
while(1) {
produce an Item in nextp;
procuder_conmuser.put(item);
}
}
void consumer(int i) {
while(1) {
consume an Item in nextc;
procuder_conmuser.out(item);
}
}
把同步机制放在管程中,避免信号量机制中每个进程都要写信号量。
这种机制类似于封装的思想。在你需要上锁的时候,只需要调用锁的函数。
也便于对锁的修改。