I'm trying to use the first response to this question to help me on an assignment I'm working on. How exactly does a Semaphore with 0 permits work? It doesn't really seem to make much sense to me. Is it just to create an eternal wait at that semaphore? If that's the case, how can you ever have a thread 'get past' the semaphore while it's just waiting for a permit that will never be given to it?
Asked
Active
Viewed 5,713 times
1 Answers
12
Again from The Little Book of Semaphores, §2.2:
Listing 2.1: Semaphore initialization syntax
fred = Semaphore(1)
The function
Semaphore
is a constructor; it creates and returns a new Semaphore. The initial value of the semaphore is passed as a parameter to the constructor.
So in the author's pseduocode, 0
isn't the number of permits; it's the initial value of the semaphore. What does a value of zero mean? It's explained in the text immediately proceeding listing 2.1:
If the value is positive, then it represents the number of threads that can decrement without blocking. If it is negative, then it represents the number of threads that have blocked and are waiting. If the value is zero, it means there are no threads waiting, but if a thread tries to decrement, it will block.
(emphases added)
-
1I see... I assume since you are emphasizing the 'initial' value, that the number of permits can be increased? So would a release() call on a Semaphore with initially 0 permits, with no prior acquire() call, now give that Semaphore 1 permit? – Hoser Feb 10 '13 at 01:06
-
In this context/usage, thinking about semaphores in terms of "permits" isn't quite correct. The value can be negative, and it doesn't make sense to think about a negative number of permits. Don't think about a semaphore's value (as used in the Book) as a number of permits. The value's meaning is exactly as described in the part I quoted. – Matt Ball Feb 10 '13 at 01:24