# 2.5.1 Semaphore

typedef struct ZixSemImpl ZixSem

  A counting semaphore.

  This is an integer that is never negative, and has two main operations: increment (post) and decrement (wait). If a decrement can’t be performed (because the value is 0) the caller will be blocked until another thread posts and the operation can succeed.

  Semaphores can be created with any starting value, but typically this will be 0 so the semaphore can be used as a simple signal where each post corresponds to one wait.

  Semaphores are very efficient (compared to a mutex/cond pair). In particular, at least on Linux, post is async-signal-safe, which means it does not block and will not be interrupted. If you need to signal from a realtime thread, this is the most appropriate primitive to use.

ZixStatus zix_sem_destroy(ZixSem *sem)

  Destroy `sem`.

  Returns:

    `ZixStatus.ZIX_STATUS_SUCCESS`, or an error.

ZixStatus zix_sem_init(ZixSem *sem, unsigned initial)

  Create `sem` with the given `initial` value.

  Returns:

    `ZixStatus.ZIX_STATUS_SUCCESS`, or an unlikely error.

ZixStatus zix_sem_post(ZixSem *sem)

  Increment and signal any waiters.

  Realtime safe.

  Returns:

    `ZixStatus.ZIX_STATUS_SUCCESS` if `sem` was incremented, `ZixStatus.ZIX_STATUS_OVERFLOW` if the maximum possible value would have been exceeded, or `ZixStatus.ZIX_STATUS_BAD_ARG` if `sem` is invalid.

ZixStatus zix_sem_timed_wait(ZixSem *sem, uint32_t seconds, uint32_t nanoseconds)

  Wait for an amount of time until count is > 0, then decrement if possible.

  Obviously not realtime safe.

  Returns:

    `ZixStatus.ZIX_STATUS_SUCCESS` if `sem` was decremented, `ZixStatus.ZIX_STATUS_TIMEOUT` if it was still zero when the timeout was reached, `ZixStatus.ZIX_STATUS_NOT_SUPPORTED` if the system does not support timed waits, or `ZixStatus.ZIX_STATUS_BAD_ARG` if `sem` is invalid.

ZixStatus zix_sem_try_wait(ZixSem *sem)

  Non-blocking version of wait().

  Returns:

    `ZixStatus.ZIX_STATUS_SUCCESS` if `sem` was decremented, `ZixStatus.ZIX_STATUS_UNAVAILABLE` if it was already zero, or `ZixStatus.ZIX_STATUS_BAD_ARG` if `sem` is invalid.

ZixStatus zix_sem_wait(ZixSem *sem)

  Wait until count is > 0, then decrement.

  Obviously not realtime safe.

  Returns:

    `ZixStatus.ZIX_STATUS_SUCCESS` if `sem` was decremented, or `ZixStatus.ZIX_STATUS_BAD_ARG` if `sem` is invalid.