Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Semaphore initialized with 1 and 0

Tags:

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); 
like image 217
Atul Kumar Avatar asked Aug 29 '14 07:08

Atul Kumar


People also ask

What happens when a semaphore is initialized to 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.

What is correct way to initialize the semaphore to 1?

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.

What does a counting semaphore initialized to 0 with a value of 0 signify?

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.

What is the initial value of semaphore?

Initially, the semaphore value is 1. When process P1 enters the critical section, the semaphore value will be 0.


1 Answers

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.

like image 125
Chip Avatar answered Sep 17 '22 15:09

Chip