Please tell what is difference Semaphore initialized with 1 and zero. as below:
public static Semaphore semOne = new Semaphore(1);
and
public static Semaphore semZero = new Semaphore(0);
If the semaphore is initialized with 0, then the first completed operation must be V. Both P and V operations can be blocked, if they are attempted in a consecutive manner. If the initial value is 0, the first completed operation must be V; if the initial value is 1, the first completed operation must be P.
sema_init(3THR) h> sem_t sem ; int pshared ; int ret ; int value ; /* initialize a private semaphore */ pshared = 0; value = 1; ret = sem_init(& sem , pshared , value ); Use sema_init(3THR) to initialize the semaphore variable pointed to by sem to value amount.
Thus, if you initialize a semaphore with value zero then every thread that attempts to sem_wait() on it will block until some thread increases its value via sem_post() . If you are using the semaphore as a mutex, as the example code does, then you could characterize that as the mutex being initially locked.
Initially, the semaphore value is 1. When process P1 enters the critical section, the semaphore value will be 0.
The argument to the Semaphore instance is the number of "permits" that are available. It can be any integer, not just 0 or 1.
For semZero
all acquire()
calls will block and tryAcquire()
calls will return false, until you do a release()
For semOne
the first acquire()
calls will succeed and the rest will block until the first one releases.
The class is well documented here.
Parameters: permits - the initial number of permits available. This value may be negative, in which case releases must occur before any acquires will be granted.
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