Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and why can a Semaphore give out more permits than it was initialized with?

I am reading the book Java Concurrency in Practice. In a section about java.util.concurrent.Semaphore, the below lines are present in the book. It is a comment about its implementation of "virtual permit" objects

The implementation has no actual permit objects, and Semaphore does not associate dispensed permits with threads, so a permit acquired in one thread can be released from another thread. You can think of acquire as consuming a permit and release as creating one; a Semaphore is not limited to the number of permits it was created with.

Can somebody explain this? I am having trouble understanding this. If we create a pool of fixed size, we create a fixed number of "permits". From the above statement, it looks like the "permits" can keep growing. Why is it designed this way?

like image 693
Vinoth Kumar C M Avatar asked Sep 26 '11 12:09

Vinoth Kumar C M


People also ask

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().

What are permits in semaphore?

Semaphore(int permits) It creates a Semaphore and parses the number of permits (initial number of permits available) as an argument. It specifies the number of threads that can share a resource at a time. The value of permits may be negative. In such a case, a release must occur before any acquires will be granted.

What should a semaphore be initialized to?

For signaling, the semaphore is initialized to 0; for mutual exclusion, the initial value is 1; for multiplexing, the initial value is a positive number greater than 1. To summarize, the general practice is that the initial value of the semaphore is the desired number of initial allowed concurrent accesses.

Can a semaphore be released by any thread?

A semaphore can be released by any thread. A thread can call a wait function repeatedly on a mutex without blocking. However, if you call a wait function twice on a binary semaphore without releasing the semaphore in between, the thread will block.


1 Answers

I think that it means the times what we may require Semaphore as the times we released "extra" and plus the permits it created with.

Such as:

Semaphore s = new Semaphore(1); // one permit when initialize

s.acquire();
s.release();

s.release(); // "extra" release.

At this moment, this semaphore allows one permit originally and one "extra" permit

like image 154
lxl Avatar answered Nov 02 '22 08:11

lxl