用信号量及其PV操作处理实际问题
将生产者和消费者问题深入理解、融会贯通。
1.书上课后练习P187-43
int B; semaphore empty;/*可用的缓冲区数*/ semaphore full;/*缓冲区内可用的产品数*/ empty=1;/*缓冲区内允许放入一件产品*/ full=0;/*缓冲区内没有产品*/ semaphore 糖,水,橘子精; cobegin Process producer(){ while(true); producer(); P(empty); append to B; if(B==橘子精){ V(p1);} else if(B==糖){ V(p2);} else(B==水){ V(p3);} V(full); } coend cobegin Process p1(){ P(full); take from B; 生产橘子汁; v(empty); }coend cobegin Process p2(){ P(full); take from B; 生产橘子汁; v(empty); }}coend cobegin Process p3(){ P(full); take from B; 生产橘子汁; v(empty); }}coend
2.IPO问题:有多个输入进程、多个处理进程和多个输出进程。输入进程把数据逐步输入到一个有M个单位缓冲区B1上,经处理进程处理之后放到有N个单位的缓冲区B2上,由输出进程进行输出。
(1).这个问题有哪些进程?进程之间有什么样的制约关系?
这个问题有输入进程,处理进程,输出进程;输入进程把数据输入之后存到缓冲区B1后,再经过处理进程处理之后放到B2缓冲区之后才能由输出进程输出。
(2).用信号量及PV操作写出这些进程之间的同步算法。
semaphore s1,s2,s3,s4; semaphore mutex1,mutex2; mutex1=1,mutex2=1; cobegin Process input(){ while(true); input(); p(s1); P(mutex1); 数据放入B1(M1); m1=(m1+1)%M v(mutex1); V(s2); }coend Process Processing(){ while(true); p(s2); P(mutex2); 在B1取出数据; out1=(out1+1)%M; Processing(); v(s1); 数据处理后放入B2(M2); m2=(m2+1)%M v(mutex2); V(s3); }coend Process output(){ while(true); p(s3); 在B2取出数据; ouput(); out2=(out2+1)%M; }coend

浙公网安备 33010602011771号