[NSWI004] a04 - Semaphore wait/trywait inconsistency

Vojtech Horky horky at d3s.mff.cuni.cz
Sat Nov 28 23:33:44 CET 2020


Hello.

Dne 28. 11. 20 v 20:49 Martin Zimen napsal(a):
> Hello,
>   I'd like to ask about behavior of sem_wait and sem_trywait. In 
> description of sem_wait
> 
>  > Decrement the value of this semaphore. If the new value would be 
> negative,
>  > block and wait for someone to call sem_post() first.
> 
> Therefore it would block iff the initial value was less or equal to 0. 
> However in sem_trywait
> 
>  >  @retval EBUSY Semaphore has value of 0 and locking would block.
> 
> Why shouldn't I return EBUSY when value is negative?
> Is there a reason I miss for which these two function behave differently?

The @retval EBUSY is a bit misleading as it expects that the value never 
drops under zero. Some implementations use negative values to track 
number of waiting threads, others stop changing the value at zero (i.e. 
you will never see a negative number). I documented it after the latter 
ones.

Sorry, feel free to replace with "@retval EBUSY Locking of the semaphore 
would block".

In other words: in both cases, the semaphore is locked if the value is 
positive. If the value is zero or negative, the function either blocks 
or returns EBUSY.


Hope this helps,
- VH


More information about the NSWI004 mailing list