[Previous] [Contents] [Next]

sem_init()

Initialize a semaphore

Synopsis:

#include <semaphore.h>

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

Library:

libc

Description:

The sem_init() function initializes the unnamed semaphore referred to by the sem argument. The initial counter value of this semaphore is specified by the value argument.

The initialized semaphore can be used in subsequent calls to sem_wait(), sem_trywait(), sem_post() and sem_destroy(). An initialized semaphore is valid until it is destroyed by the sem_destroy() function, or until the memory where the semaphore resides is released.

If the pshared argument is nonzero, then the semaphore can be shared between processes via shared memory. Any process can then use sem with the sem_wait(), sem_trywait(), sem_post() and sem_destroy() functions.

Returns:

0
Success. The semaphore referred to by sem is initialized.
-1
An error occurred (errno is set).

Errors:

EAGAIN
A resource required to initialize the semaphore has been exhausted.
EINVAL
The value argument exceeds SEM_VALUE_MAX.
EPERM
The process lacks the appropriate privileges to initialize the semaphore.
ENOSPC
A resource required to initialize the semaphore has been exhausted.
ENOSYS
The sem_init() function isn't supported.

Classification:

POSIX 1003.1

Safety:
Cancellation point No
Interrupt handler No
Signal handler No
Thread Yes

Caveats:

Don't initialize the same semaphore from more than one thread. It's best to set up semaphores before starting any threads.

See also:

errno, sem_destroy(), sem_post(), sem_trywait(), sem_wait()


[Previous] [Contents] [Next]