I am studying for a midterm and this was one of the practice questions: Show how counting semaphores (i.e, semaphores that can hold an arbitrary value) can be implemented using only binary semaphores and ordinary machine instructions?
I'm not even sure where so start. I found this online;
P(s) { Pb(mutex_s); s = s-1; if(s < 0) {Vb(mutex_s); Pb(delay_s);} Vb(mutex_s); }
V(s) { Pb(mutex_s); s = s+1; if(s <= 0) Vb(delay_s); else Vb(mutex_s); }
Unfortunately, I don't really understand what the answer is telling me. Can anyone explain this answer to me, or show me in pseudo code how to answer?
A semaphore is a signaling mechanism, and a thread that is waiting on a semaphore can be signaled by another thread. It uses two atomic operations, 1) Wait, and 2) Signal for the process synchronization. A semaphore either allows or disallows access to the resource, which depends on how it is set up.
A binary semaphore is restricted to values of zero or one, while a counting semaphore can assume any nonnegative integer value. A binary semaphore can be used to control access to a single resource. In particular, it can be used to enforce mutual exclusion for a critical section in user code.
I built the following intuition on Prahbat's answer:
What we are trying to replicate:
We can do this using binary semaphores:
Thus the following pseudocode suggests itself
P_counting( int count )
P( countLock ) // Acquire lock to count: countLock <- 0
count--
if( count <= 0 ) // If no more threads allowed into critical section
P( sectionLock ) // Resource full => Acquire section lock: sectionLock <- 0
V( countLock ) // Release lock to count: countLock <- 1
else
V( countLock)
V_counting( int count )
P( countLock )
count++
if( count > 0) // Release sectionLock if resource is freed up
V(sectionLock) // countLock released after sectionLock so that waiting
V(countLock) // threads do not jump in when before resource is available
else
V(countLock)
Please let me know if I have got something wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With