如果您无法下载资料,请参考说明:
1、部分资料下载需要金币,请确保您的账户上有足够的金币
2、已购买过的文档,再次下载不重复扣费
3、资料包下载后请先用软件解压,在使用对应软件打开
各章例题集第二章进程管理1.利用记录型信号量解决生产者—消费者问题Varempty,full:semaphore:=1,0;buffer:array[1]ofitem;beginparbeginproducer:beginrepeatwait(empty);putdata;signal(full);untilfalse;end复杂情况(既有同步,又有互斥):一个buffer,多个生产者,多个消费者,生产者不断地生产,消费者不断地消费。只有buffer为空时生产者才能进行putdata操作,只有buffer有数据时消费者才能进行getdata操作。Varmutex,empty,full:semaphore:=1,1,0;buffer:array[1]ofitem;beginparbeginproducer:beginrepeatwait(empty);wait(mutex);putdata;signal(mutex);signal(full);untilfalse;end一般意义的“生产者—消费者”问题:N个buffer,多个生产者,多个消费者,循环存取buffer。(教材上的)1.利用记录型信号量解决生产者—消费者问题假定:在P-C之间的公用缓冲池中,具有n个缓冲区;利用互斥信号量mutex实现各进程对缓冲池的互斥使用;利用信号量empty和full分别表示缓冲池中空缓冲区和满缓冲区的数量。这些生产者和消费者相互等效,只要缓冲池未满,生产者便可将消息送入缓冲池;只要缓冲池未空,消费者便可从缓冲池中取走一个消息。每个进程中各个P操作的次序很重要:先检查资源数目,再检查是否互斥――否则可能死锁Varmutex,empty,full:semaphore∶=1,n,0;buffer:array[0,…,n-1]ofitem;in,out:integer∶=0,0;beginparbeginproceducer:beginrepeat…produceranitemnextp;…wait(empty);wait(mutex);buffer(in)∶=nextp;in∶=(in+1)modn;signal(mutex);signal(full);untilfalse;endconsumer:beginrepeatwait(full);wait(mutex);nextc∶=buffer(out);out∶=(out+1)modn;signal(mutex);signal(empty);consumertheiteminnextc;untilfalse;endparendend练习semaphorechopstick[5]={1,1,1,1,1};semaphorecount=4;voidphilosopher(inti){while(true){think();wait(count);//请求进入房间进餐wait(chopstick[i]);//请求左手边的筷子wait(chopstick[(i+1)%5]);//请求右手边的筷子eat();signal(chopstick[(i+1)%5]);//释放右手边的筷子signal(chopstick[i]);//释放左手边的筷子signal(count);//退出房间释放信号量room}}14利用AND信号量机制解决哲学家进餐问题armutex,empty,full:semaphore∶=1,n,0;buffer:array[0,…,n-1]ofitem;inout:integer∶=0,0;beginparbeginproducer:beginrepeat…produceaniteminnextp;…Swait(empty,mutex);buffer(in)∶=nextp;in∶=(in+1)modn;Ssignal(mutex,full);untilfalse;end读者-写者问题可描述如下:Varrmutex,wmutex:semaphore∶=1,1;Readcount:integer∶=0;beginparbeginReader:begin//读者repeatwait(rmutex);ifreadcount=0thenwait(wmutex);Readcount∶=Readcount+1;sign