Multithreaded Programming Guide

Decrement a Semaphore Count

sem_trywait(3RT)

Prototype:
int	sem_trywait(sem_t *sem);
#include <semaphore.h>

sem_t sem;
int ret;

ret = sem_trywait(&sem); /* try to wait for semaphore*/

Use sem_trywait(3RT) to try to atomically decrement the count in the semaphore pointed to by sem when the count is greater than zero. This function is a nonblocking version of sem_wait(); that is it returns immediately if unsuccessful.

Return Values

sem_trywait() returns zero after completing successfully. Any other return value indicates that an error occurred. When any of the following conditions occurs, the function fails and returns the corresponding value.


EINVAL

sem points to an illegal address.


EINTR

A signal interrupted this function.


EAGAIN

The semaphore was already locked, so it cannot be immediately locked by the sem_trywait() operation.