资源描述:
《《操作系统教学资料》关于pv操作习题的讨论130602》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、38独木桥问题3:在独木桥问题1中,以畚辆汽车为一组,要求保证左方和右方以组为单位交替通过汽车。试用信号量和p,v操作写出汽车过独木桥问题的同步算法。解[:varwait,mutexlmutex2:semaphore;mutexl:=mutex2:=l;wait:=l;Sl=3;S2=0;countl/count2:integer;processPLi(){while(true){P(S1)P(mutexl);countl++;if(countl==l)P(wait);V(mutexl);过独木桥
2、;V(S2)P(mutexl);countl-;if(countl=0)V(wait);V(mutexl);}}processPRi(){while(true){P(S2)P(mutex2);count2++;if(count2==l)P(wait);V(mutex2);过独木桥;V(S1)P(mutex2);count2-;if(count2==0)V(wait);V(mutex2);}}用表格给出了下面的执行示例:其中PL1表示P左:LPL2表示P左2,PR1表示P右:1,PR2表示P右2,序
3、调用进程被调用的操作信号量状态1・PLIP(S1)Sl=2,S2=0,mutexl=bmutex2=lzwait=l2・PR1P(S2)S1=2ZS2=-l(PR1),mutexl=l,mutex2=l,wait=l3・PLIP(mutexl)S2=-l(PR1)#mutexl=0,mutex2=l#wait=l4・PLIP(wait)SI二乙S2=-l(PR1),mutexl=0,mutex2=l,wait=05・PLIV(mutexl)SI二乙S2=-l(PR1),mutexl=l,mutex
4、2=l,wait=06・PLIV(S2)Sl=2,S2=0PR1(),mutexl=l,mutex2=l,wait=07・PR1P(mutex2)S2=0,mutexl=l,mutex2=0#wait=0&PR1P(wait)S2=0,mutexl=l,mutex2=0/wait=-l(PR1)9・PLIP(mutexl)Sl=2,S2=0zmutexl=0,mutex2=0zwait=-l(PR1)10.PLIV(wait)Sl=2,S2=0,mutexl=0#mutex2=0fwait=0PR
5、1()11.PR1V(mutex2)SI二乙S2=0,mutexl=0zmutex2=l,wait=012.PLIV(mutexl)S1=2ZS2=0,mutexl=l/mutex2=l/wait=013.PR1V(S1)Sl=3#S2=0#mutexl=l/mutex2=0#wait=014.PR1P(mutex2)Sl=3,S2=0#mutexl=l,mutex2=0,wait=015.PR1V(wait)Sl=3#S2=0#mutexl=l/mutex2=0#wait=l16.PR1V(mu
6、tex2)S1=3ZS2=0#mutexl=l/mutex2=l/wait=l17.18.19.有可能对对上述解做修改,如下:解2:semaphorewai^mutex^mutexZ;mutexl=mutex2=l;wait=l;intcountl,count2;countl=0;count2=0;semaphoreS1/S2;S1=3;S2=O;processPLi(){processPRi(){while(true){while(true){P(S1)P(S2)P(mutexl);P(mute
7、x2);countl++;count2++;if(countl==l)P(wait);if(count2==l)P(wait);V(mutexl);V(mutex2);过独木桥;过独木桥;V(S2)V(S1)P(mutexl);P(mutex2);if(countl=3)count2~;{countl==0;V(wait);}if(count2==3)V(mutexl);{count2==0;V(wait);}}V(mutex2);}}}执行序列为PL1上桥,PL2上桥,PL3上桥,PL1下桥,P
8、R1上桥,PL1,PL乙PL3,PR1四个进程的执行情况配有不同的底色,详见下表:初值Sl=3;S2=0;mutexl=l;mutex2=l;wait=l;countl=0;count2=0;序调用进程执行语句信号量状态1・PL1P(S1)Sl=2;S2=0;mutexl=l;mutex2=l;wait=l;countl=0;count2=0;2・PL1P(mutexl)Sl=2;S2=0;mutexl=O;mutex2=l;wait=l;countl=0;count2=0;3・P