Anish Ghosh
Anish Ghosh

Reputation: 19

Why do we use less-than-or-equals (<=) symbol in semaphores?

While implementing the waiting code in a semaphore we use the following code:

wait(semaphore s) { while(s<=0); s -= 1;}

Instead we can use:

wait(semaphore s) { while(s==0); s -= 1;}

The result will be same. Then why do most of all prefer using the first one?

Upvotes: 1

Views: 35

Answers (1)

Daniel Jour
Daniel Jour

Reputation: 16156

A (counting) semaphore may be initialized with a negative value, for example to have a single thread wait until 5 other threads arrive at a specific point:

shared:
  semaphore with counter initialised to -4

waiter thread:
  wait(semaphore)
  print "Done waiting"

other threads:
  incredible important work
  post(semaphore)

Therefore, you need to also check for negative counter values.

Upvotes: 1

Related Questions