---
name: "sem_wait"
section: "2"
platform: "macos"
package: "xnu"
version: "12377.121.6"
release: "macOS 26.5"
platforms: ["macos"]
url: "https://new.carta.tech/sem_wait"
---

# sem\_wait(2)

lock a semaphore

## NAME

**sem\_trywait,** **sem\_wait** – lock a semaphore

## SYNOPSIS

**#include \<semaphore.h\>**

*int*\

**sem\_trywait**(*sem\_t \*sem*);

*int*\

**sem\_wait**(*sem\_t \*sem*);

## DESCRIPTION

The semaphore referenced by *sem* is locked.  When calling **sem\_wait**(), if the semaphore's value is zero, the calling thread will block until the lock is acquired or until the call is interrupted by a signal. Alternatively, the **sem\_trywait**() function will fail if the semaphore is already locked, rather than blocking on the semaphore.

If successful (the lock was acquired), **sem\_wait**() and **sem\_trywait**() will return 0.  Otherwise, -1 is returned and *errno* is set, and the state of the semaphore is unchanged.

## ERRORS

**sem\_wait**() and **sem\_trywait**() succeed unless:

- \[EAGAIN\]

  The semaphore is already locked.

- \[EDEADLK\]

  A deadlock was detected.

- \[EINTR\]

  The call was interrupted by a signal.

- \[EINVAL\]

  *sem* is not a valid semaphore descriptor.

## NOTES

Applications may encounter a priority inversion while using semaphores.  When a thread is waiting on a semaphore which is about to be posted by a lower-priority thread and the lower-priority thread is preempted by another thread (of medium priority), a priority inversion has occured, and the higher-priority thread will be blocked for an unlimited time period.  Programmers using the realtime functionality of the system should take care to avoid priority inversions.

## SEE ALSO

[sem\_open(2)](/sem_open/2.md), [sem\_post(2)](/sem_post/2.md), [semctl(2)](/semctl/2.md), [semget(2)](/semget/2.md), [semop(2)](/semop/2.md)

## HISTORY

**sem\_wait**() and **sem\_trywait**() are specified in the POSIX Realtime Extension (1003.1b-1993/1003.1i-1995).
