Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero permit semaphores?

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?

like image 696
Hoser Avatar asked Feb 10 '13 00:02

Hoser


People also ask

What happens when semaphore is 0?

If the value of the semaphore is zero, then the current thread will block until the semaphore's value becomes greater than zero.

What are permits in semaphore?

the constructor parameter permits (initial semaphore counter) is the number of calls to Semaphore. aquire() that can be made before the counter (permits) is zero, and the acquire() blocks.

Why the semaphore full is initialized to be 0?

Semaphore 'full' is initialized to '0'. This means there is no item in the buffer. Semaphore 'empty' is initialized to 'n'. This means there is space for n items in the buffer.

Can thread release permits on a semaphore without having them?

There is no requirement that a thread that releases a permit must have acquired that permit by calling acquire().


1 Answers

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)

like image 143
Matt Ball Avatar answered Nov 05 '22 12:11

Matt Ball