生产消费者模型
多生产者多消费者模型
单生产者多消费者模型
哲学家进餐
生产消费者模型
P()进程需向互斥缓冲区进行写操作,而C()进程从互斥缓冲区进行取操作。
==分析:P和C互斥访问同一临界资源,需设置mutex=1;
P和C相互同步,P提供产品给C,而C提供空间给P
semaphore mutex=1,empty=n,product=0;
P(){
while(1){
make ;
P(empty);
P(mutex);
remove to ;
V(mutex);
V(product);
}
}
C(){
while(1){
P(product):
P(mutex);
remove;
V(mutex):
V(empty):
consume;
}
}
多生产者多消费者模型
当缓冲区大小为1时,只会有1个进程进行,此时无需设置对缓冲区的互斥信号量
semaphore empty=1;apple=0,orrange=0;
P1(){
while(1){
make;
P(empty);
add;
V(apple);
}
}
P2(){
while(1){
make;
P(empty);
add;
V(orrange):
}
}
C1(){
while(1){
P(apple):
remove;
V(empty):
consumer;
}
}
C2(){
while(1){
P(orrange):
remove;
V(empty);
consumer;
}
}
单生产者多消费者模型
int i =0;
semaphore full1=0,full2=0,full3=0,empty=1;
P(){
while(1){
P(empty):
if(i==0)
V(full1);
else if(i==1)
V(full2);
else
V(full3);
i=(i+1)%3;
}
}
Ci(){
while(1){
P(fulli);
remove;
V(empty);
consumer;
}
}
读写模型
分析:
读进程与写进程互斥,需设置互斥量mutex=1;
写进程与写进程互斥,可使用互斥量mutex;
读进程与读进程不互斥,因此需区分第一个读进程与之后的读进程,只在第一个读进程进行P(mutex);
还需设置互斥量protect=1用于保护计数过程
semaphore mutex=1,protect=1;
int count=0;
W(){
while(1){
P(mutex);
write;
V(mutex);
}
}
R(){
while(1){
P(protect);
if(count==0)
P(mutex):
count++;
V(protect):
read;
P(protect);
count--;
if(count==0)
V(mutex);
V(protect);
}
}
哲学家进餐
分析:
为避免死锁,可通过设置信号量mutex=1做到只允许一个人进餐;
为每一个资源设置信号量tag[i]=1;
semaphore tag[5]={1,1,1,1,1},mutex=1;
Ci(){
while(1){
P(mutex);
P(tag[i]);
P((tag[i+1)%5]);
V(mutex);
eat;
V(tag[i]);
V((tag[i+1)%5]);
}
}