sem_wait(3pthread)


sem_wait, sem_trywait -- lock, attempt to lock, a semaphore

Synopsis

   cc [options] -Kthread file
   

#include <semaphore.h>

int sem_wait(sem_t *sem); int sem_trywait(sem_t *sem);

Description

sem_wait acquires the semaphore pointed to by sem In general, sem_wait is used to block wait for an event, or when a critical section is long. Semaphores are asynchronous-safe, and can be used to communicate between signal handlers and base level code.

If the semaphore is available (that is, if the semaphore value is greater than zero), sem_wait decrements the semaphore value and returns to the caller.

If the semaphore is unavailable (that is, the semaphore value is zero or less), sem_wait decrements the semaphore value and suspends execution of the calling thread until the semaphore becomes available to the caller or the call is interrupted by a signal.

If a thread waiting on a semaphore is interrupted by a signal, sem_wait returns EINTR.

sem_trywait makes a single attempt to acquire the semaphore pointed to by sem. If the semaphore is available, sem_trywait decrements the semaphore value and returns to the caller. sem_trywait is used when the caller does not want to block if the semaphore is unavailable. If sem_trywait cannot immediately acquire the semaphore, it returns EAGAIN to the caller, it does not block the caller to wait for the semaphore or decrement the semaphore value.

sem is a pointer to the semaphore to acquire, which must previously have been initialized by sem_init.

Return values

sem_wait and sem_trywait return zero for success. If the call was unsuccessful, the state of the semaphore is unchanged, and the function returns a value of -1 and sets errno to indicate the error.

Diagnostics

sem_wait and sem_trywait return -1 and set errno to the following value if the corresponding condition is detected:

EINVAL
sem does not refer to a valid semaphore.

sem_wait returns a value of -1 and sets errno to the following value if the corresponding condition is detected:


EINTR
a signal interrupted this function.

sem_trywait returns the following value if the corresponding condition is detected:


EAGAIN
The semaphore was already locked, so it cannot be immediately locked by sem_trywait.

Standards compliance

The Single UNIX Specification, Version 2; The Open Group.

References

Intro(3pthread), sem_destroy(3pthread), sem_init(3pthread), sem_post(3pthread), sem_trywait(3pthread), semaphore(4)
© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 25 April 2004