1.同步问题
semaphore S=0;
P1(){
x;
V(S);
}
P2(){
P(S);
y;
}
2.互斥问题
semaphore S=1;
P1(){
P(S);
进程P1进入临界区;
V(S);
}
P2(){
P(S);
进程P2进入临界区;
V(S);
}
3.生产者消费者问题
semaphore mutex1;
semaphore empty = n;
seamphore full = 0;
product{
while(1){
product an item in nextp;
P(empty);
P(mutex);
add nextp to buffer;
V(mutex);
V(full);
}
}
consumer{
while(1){
P(full);
P(mutex);
remove an item from buffer;
V(mutex);
V(empty);
comsume the item;
}
}
4.吃水果问题
桌上有一只盘子,每次只能放一个水果,爸爸专向盘中放苹果,妈妈专向盘中放桔子,儿子专等吃盘里的桔子,女儿专等吃盘里的苹果。只要盘子空,则爸爸或妈妈可向盘中放水果,仅当盘中有自己需要的水果时,儿子或女儿可从中取出,请给出四人之间的同步关系,并用P、V操作实现四人正确活动的程序。
父亲和母亲先放水果,儿子女儿再取水果;父亲与女儿,母亲与儿子是一个同步关系,父亲与母亲要竞争空盘子,但空盘子容量为2.
设信号量m1表示盘子空位,信号量m2表示儿子是否能取苹果,m3表示女儿能否取桔子。
int m1=2,m2=0,m3=0;
p1(){
while(1){
洗桔子;
P(m1);
放桔子;
V(m3);
}
}
p2(){
while(1){
洗苹果;
P(m1);
放苹果;
V(m2);
}
}
p3(){
while(1){
P(m2);
取苹果;
V(m1);
吃苹果;
}
}
p4(){
while(1){
P(m3);
取桔子;
V(m1);
吃桔子;
}
}
5.哲学家进餐问题
semaphore chopstick[5] = {1, 1, 1, 1, 1};
semaphore mutex = 1;
Pi(){
do{
P(mutex);
P(chopstick[i])
P(chopstick[i][(i+1)%5]);
V(mutex)
eat;
V(chopstick[i]);
V(chopstick[i][(i+1)%5]);
think;
}while(1);
}
6.读者-写者问题
int count = 0;
semaphore mutex = 1;
semaphore rw = 1;
writer(){
while(1){
P(rw);
writeing;
V(rw);
}
}
reader(){
while(1){
P(mutex);
if(count == 0)
P(rw);
count++;
V(mutex);
reading;
P(mutex);
count--;
if(count == 0)
V(rw);
V(mutex);
}
}
7.吸烟者问题
int num=0;
semaphore offer1=0;
semaphore offer2=0;
semaphore offer3=0;
semaphore finish=0;
process P1(){//供应者
num++;
num = num%3;
if(num==0)
V(offer1);
else if(num==1)
V(offer2);
else
V(offer3);
P(finsh);
}
process P2(){
while(1){
P(offer1);
拿....
V(finish);
}
}
process P2(){
while(1){
P(offer2);
拿....
V(finish);
}
}
process P2(){
while(1){
P(offer3);
拿....
V(finish);
}
}
评论区