第五讲进程同步与通信partII.ppt
文本预览下载声明
Readers-Writers problem (cont’d) 写者对共享数据具有独占性 读者-写者问题的变形: The first R/W problem Reader has the higher priority Writer may starve The second R/W problem Writer has the higher priority Reader may starve R/W problem: a solution Shared variable int readcount = 0; Shared semaphore semaphore Wmutex=1; semaphore Rmutex = 1; Writer do{ P(Wmutex); /* perform write operation */ V(Wmute); }while(1); Reader do{ P(Rmutex); if (readcount==0) P(Wmutex); readcount++; V(Rmutex); /* perform read operation */ P(Rmutex); readcount--; if (readcount==0) V(Wmutex); V(Rmutex); }while(1); 利用信号量集解决读者-写者问题 假定最多只允许RN个读者 使用信号量L控制读者的数量 var RN integer; L, mx:semaphore:=RN,1; reader: begin repeat Swait(L,1,1); Swait(mx,1,0); … read … Ssignal(L,1); until false; end writer: beginrepeat Swait(mx,1,1; L,RN,0); …write… Ssignal(mx,1)end Dining-Philosophers Problem哲学家就餐问题 5 philosophers Thinking or eating Only 5 chopsticks Left right One at a time At most 2 philosophers can eat at a time semaphore chopstick[5] ={1,1,1,1,1}; Dining-philosophers problem (cont.) A possible solution Philosopher i Possible deadlock When 5 philosophers each grabs the left chopstick, … Solutions: Philosophers =4 Only if both chopsticks are available, … Odd, first left then right; even, first right then left do{P(chopstick[i]); // leftP(chopstick[(i+1)%5]; // right /* eating */ V(chopstick[i]; V(chopstick[(i+1)%5]; /* thinking */ }while(1); 利用AND信号量解决哲学家就餐问题 var chopstick array of semaphore:=(1,1,1,1,1)process i repeat think; Swait(chopstick[(i+1)mod5], chopstick[i]); eat; Ssignal(chopstick[(i+1)mod5], chopstick[i]); until false; Timing errors Only happen when some particular execution sequences take place For example: counter++; counter--; Difficult to detect Do
显示全部