40 likes | 47 Views
This article discusses a correct and unrestrictive implementation of general semaphores for process synchronization, including a solution for avoiding lost signals and potential scheduling restrictions. The proposed solution improves upon the flawed original implementation and ensures that processes waiting on the counting semaphore are properly signaled.
E N D
Further Comments on a Correct and Unrestrictive Implementation of General Semaphores
void semWait(semaphore s) { semWaitB(mutex); s--; if (s<0) { semSignalB(mutex); semWaitB(delay); } else semSignalB(mutex); } void semSignal(semaphore s) { semWaitB(mutex); s++; if (s<=0) semSignalB(delay); semSignalB(mutex); } Start with four processes, P1 thru P4 , s = 0, delay = 0 P1 and P2 arrive at arrow, s =-2 P3 completes semSignal,s = -1, delay = 1 P4 completes semSignal,s = 0, delay = 1 But P4’s signal to delay is lost! If P1 proceeds, P2 will be stuck just after the arrow, until another semSignal is called. Original (flawed) solution
void semWait(semaphore s) { semWaitB(mutex); s--; if (s<0) { semSignalB(mutex); semWaitB(delay); } semSignalB(mutex); } void semSignal(semaphore s) { semWaitB(mutex); s++; if (s<=0) semSignalB(delay); else semSignalB(mutex); } Make access to the counting semaphore, s, conditional during semSignal such that if any processes are currently waiting on it, ie executing inside semWait, mutex will not be signaled. Caveat: can impose a severe scheduling restriction on the processes. Once processes start to wait on delay, forces a lock step behavior. Imagine producer/consumer scenario. A working solution
void semWait(semaphore s) { semWaitB(delay); semWaitB(mutex); s--; if (s>0) semSignalB(delay); semSignalB(mutex); } void semSignal(semaphore s) { semWaitB(mutex); s++; if (s==1) semSignalB(delay); semSignalB(mutex); } mutex = 1, s = initial value, delay = min(1, initial value) Once a process has passed either semWaitB(mutex), s will be modified, delay will be conditionally signaled, and the critical section will be released. The value of s is not allowed to become smaller than zero. Only processes that can execute semWait completely, once s is free, are allowed to continue past semWaitB(delay). Is deadlock or starvation possible? Solution proposed by Barz