Consider four processes A, B, C and D, sharing a same buffer. Process A inputs one object into the buffer each time, and it will not input the next object until that all process B, C and D have accessed the object once.
(1) How many semaphores will be needed for correct communication among process A, B, C and D?
(2) Try to solve the above scene’s synchronization and mutex using P, V operations.
这是一道华为面试题,在这里我把自己的思路写一下,供大家参考。
(1)设置4个信号量,mutexB=mutexC=mutexD=1;int s=0;//s=1表示A已经生产
(2)process A:
while(true){
Wait(mutexB);
Wait(mutexC);
Wait(mutexD);
S=0;
//produce item
S=1;
signal(mutexB);
signal(mutexC);
signal(mutexD);
}
Process B:
While(true){
Wait(mutexB);
If(s==1){
//consume item;
}
Signal(mutexB);
}//进程C、D跟B同理