用信号量实现互斥并发
Var mutex:semaphoer:=1; Begin Parbegin Process1:begin //第一个进程 repeat wait(mutex); critical section signal(mutex); remainder section until false; end; Process2:begin //第二个进程 repeat wait(mutex); //申请资源 critical section //使用临界区 singal(mutex); //释放资源 remainder section //剩余区代码 until false; end Parend
一组生产者进程生产产品给一组消费者进程消费。为使他们并发执行,设一个有n个缓冲区的缓冲池,生产者一次向一个缓冲区中投入消息,消费者从一个缓冲区中取得消息。生产者——消费者问题其实是相互合做进程关系的一种抽象。code
var mutex:semaphore:=1; empty:semaphore:=n; full:semaphore:=0; buffer:array[0,1,……,n-1] of item; //生产者生产出来的一个数据就是item in,out:integer:=0,0; //in记录放入数据的地址,out记录取出数据的地址,其实就是buffer下标
生产者进程:进程
Procedure:begin repeat …… procedure an item nextp; //生产一个数据(下一个) …… wait(empty); //申请一个空缓冲区,申请成功,empty信号量减1 wait(mutex); Buffer(in):=nextp; //将nextp放入下标是in的缓冲区中 in:=(in+1) mod n; singal(mutex); //释放缓冲区 singal(full); //将full信号量加1 until false; end;
消费者进程资源
consumer:begin repeat wait(full); //申请一个缓冲区 wait(mutex); //含义是判断当前有没有生产者在使用申请的缓冲区 nextc:=Buffer(out); out:=(out+1) mod n; singal(mutex); singal(empty); //释放一个空缓冲区,empty加1 Consumer the item in nextc; until false; end;