program sample; var c1,c2:integer; procedure p1 begin repeat other section 1; repeat c1 =1-c2; until c2!=0 critical section;//临界区 c1 =1; until false end procedure p2 begin repeat other section 2; repeat c2 =1-c1; until c1!=0 critical section;//临界区 c2 =1; until false end begin c1 =1; c2 =1; cobegin p1; p2;//进程p1,p2并行执行 end
var mutex=1,count=1:semaphore; cobegin process Readeri(i=1,2) begin repeat 进入图书馆; p(count); p(mutex); i = 获取座位号; 登记i项表目(名字,座位号); v(mutex); 坐下阅读; p(mutex); 消去登记项(名字,座位号) v(mutex); v(count); 离开; until false end
var sa=1,sb=1,mutex=1,c1=0,c2=0,k1=0,k2=0:semaphore; cobegin process 甲 begin L1:p(mutex); p(sa); c1 = c1 +1; v(sa); if(c1<=100) then begin 从标志为“B"且不为”Sb"或无标识的毕业生队列中选第i个学生将学生i标识为"A"和"sa" end v(mutex); 面试; p(mutex); if 合格 then begin k1 = k1 +1; if(学生i的标识不含"B") then begin p(sb); c2 = c2+1; v(sb); 将学生i从队列上摘除; end else 将学生 i从队列上摘除; else if(学生i的标识含“B”)then 将学生i从队列上摘除 else 取消学生i的"sa"标识; v(mutex); if(k1<10) and (c1<100) then goto L1 end v(s2); until false end process 乙 begin L2:p(mutex); p(sa); c2 = c2 +1; v(sb); if(c2<=100) then begin 从标志为“A"且不为”Sa"或无标识的毕业生队列中选第i个学生将学生i标识为"B"和"sb" end v(mutex); 面试; p(mutex); if 合格 then begin k2 = k2 +1; if(学生i的标识不含"A") then begin p(sa); c1 = c1+1; v(sa); 将学生i从队列上摘除; end else 将学生 i从队列上摘除; else if(学生i的标识含“A”)then 将学生i从队列上摘除 else 取消学生i的"sb"标识; v(mutex); if(k2<10) and (c2<100) then goto L2 end v(s2); until false end