Semaphores

Lightweight semaphore implementation.

enum sema_state_t
SEMA_OK = 0
SEMA_DESTROY
void sema_create(sema_t * sema, unsigned int value)

Creates semaphore dynamically.

See also

The Open Group Base Specifications Issue 7, sem_init() (without pshared parameter)

Parameters

sema:The created semaphore.
value:Initial value for the semaphore.

void sema_destroy(sema_t * sema)

Destroys a semaphore.

Destroying a semaphore upon which other threads are currently blocked will wake the other threads causing the sema.h::sema_wait() (or sema.h::sema_wait_timed()) to return error (-ECANCELED).

Parameters

sema:The semaphore to destroy.

int _sema_wait(sema_t * sema, int block, uint64_t timeout)

Wait for a semaphore, blocking or non-blocking.

For commit purposes you should probably use sema.h::sema_wait(), sema.h::sema_wait_timed() and sema.h::sema_try_wait() instead.

Parameters

sema:A semaphore.
block:if true, block until semaphore is available.
timeout:if blocking, time in microseconds until the semaphore times out. 0 waits forever.

Return values

  • 0 on success
  • -ETIMEDOUT, if the semaphore times out.
  • -ECANCELED, if the semaphore was destroyed.
  • -EAGAIN, if the semaphore is not posted (only if block = 0)
int sema_wait_timed(sema_t * sema, uint64_t timeout)

Wait for a semaphore being posted.

Parameters

sema:A semaphore.
timeout:Time in microseconds until the semaphore times out. 0 does not wait.

Return values

  • 0 on success
  • -ETIMEDOUT, if the semaphore times out.
  • -ECANCELED, if the semaphore was destroyed.
  • -EAGAIN, if the semaphore is not posted (only if timeout = 0)
int sema_wait(sema_t * sema)

Wait for a semaphore being posted (without timeout).

Parameters

sema:A semaphore.

Return values

  • 0 on success
  • -ECANCELED, if the semaphore was destroyed.
int sema_try_wait(sema_t * sema)

Test if the semaphore is posted.

This is a non-blocking alternative to sema.h::sema_wait().

Return values

  • 0 on success
  • -EAGAIN, if the semaphore is not posted.
  • -ECANCELED, if the semaphore was destroyed.
int sema_post(sema_t * sema)

Signal semaphore.

Parameters

sema:A semaphore.

Return values

  • 0, on success
  • -EOVERFLOW, if the semaphore’s value would overflow.
SEMA_CREATE( value)

Creates semaphore statically.

1
{ (value), SEMA_OK, MUTEX_INIT }

Parameters

value:Initial value for the semaphore (can’t be 0). For a 0 initialized semaphore

Return values

  • Statically initialized semaphore.
SEMA_CREATE_LOCKED()

Creates semaphore statically initialized to 0.

1
{ (0), SEMA_OK, MUTEX_INIT_LOCKED }

Return values

  • Statically initialized semaphore.
struct sema_t

A Semaphore.

unsigned int value

value of the semaphore

sema.h::sema_state_t state

state of the semaphore

mutex_t mutex

mutex of the semaphore