Skip to content

sem_init

sem_init() initializes an unnamed POSIX semaphore.

Prototype

#include <semaphore.h>

int sem_init(sem_t *sem, int pshared, unsigned int value);

Parameters

Parameter Description
sem Semaphore object to initialize
pshared 0 for thread-shared, non-zero for process-shared
value Initial semaphore count

Typical Process-Shared Usage

if (sem_init(&shared->sem, 1, 0) != 0) {
    perror("sem_init");
    return -1;
}

Return Value

  • 0 on success
  • -1 on error, with errno set

Common Pitfalls

Warning

For process-shared use, the sem_t object must be stored in shared memory.

Note

Use sem_wait() to consume a count and sem_post() to produce a count.