Difference between Semaphore initialized 1 and 0

Tell us what the difference is. The semaphore is initialized to 1 and zero. as shown below:

public static Semaphore semOne = new Semaphore(1);

      

and

public static Semaphore semZero = new Semaphore(0);

      

+3


source to share


3 answers


The Semaphore instance argument is the number of "permissions" available. It can be any integer, not just 0 or 1.

For semZero

all calls are acquire()

blocked and tryAcquire()

calls return false until you dorelease()

For the semOne

first calls acquire()

will be successful and the rest will be blocked until the first is released.



The class is well documented here .

Parameters: Allows - the initial number of permissions is available. This value can be negative, in which case the releases must be purchased.

+5


source


the constructor parameter permits

(initial semaphore count) is the number of calls Semaphore.aquire()

that can be made before the (permissions) counter is zero and the blocks are acquire()

.

1 is a normal value to ensure that only one stream transmits to acquire.

semaphore.acquire();
try {
    // Critical region
    ...
} finally {
    semaphore.release();
}

      



For use of 0 see here .

Semaphore is a low level mechanism for concurrency: a counter when a blocking thread reaches zero. This is related to Dijkstra , where the binary semaphore (0, 1) is a metaphor for a railroad semaphore, passing a pass (stop at 0, transmit --permits), and at the end of the protected track, release (++ enables).

+3


source


When I first read the Semaphore documentation, I also misinterpreted the explanation. The main thing I missed was the "... INITIAL permissions ..." part. Anyway, although this will be the number of permissions that will be available as MAXIMUM, it is not. At the end, the semaphore just counts from any number, but only starts pending include threads (which use receive) when the semaphore resolves above 1.

The simple part of the code (non threading) also shows this:

@Test
public void testNegativeSemaphore()
{
    Semaphore semaphore = new Semaphore(-2);

    assertEquals(-2, semaphore.availablePermits());
    semaphore.release();
    assertEquals(-1, semaphore.availablePermits());
    semaphore.release();
    assertEquals(0, semaphore.availablePermits());
    semaphore.release();
    assertEquals(1, semaphore.availablePermits());
}

      

As the code shows, the available permissions increase with each release, only to allow other threads to receive the permission after reaching a value of 1 or higher.

NOTE that from there the available Permits cannot become negative with aqcuire, because if there is a 0, the entire semaphore point must wait for permission to become available again!

0


source







All Articles