sem_init()

Инициализировать безымянный семафор

Прототип:

#include <semaphore.h>
int sem_init( sem_t *sem,
int pshared,
unsigned value );

Аргументы:

sem
A pointer to the sem_t object for the semaphore that you want to initialize.
pshared
Nonzero if you want the semaphore to be shared between processes via shared memory.
value
The initial value of the semaphore. A positive value (i.e. greater than zero) indicates an unlocked semaphore, and a value of 0 (zero) indicates a locked semaphore. This value must not exceed SEM_VALUE_MAX.

Библиотека:

libc

Описание:

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.


Caution: You should allocate synchronization objects only in normal memory mappings. On certain processors (e.g. some PPC ones), atomic operations such as calls to pthread_mutex_lock() will cause a fault if the control structure is allocated in uncached memory.

You can use the initialized semaphore in subsequent calls to sem_wait(), sem_trywait(), sem_post(), and sem_destroy(). An initialized semaphore is valid until it's 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.


Note: Don't mix named semaphore operations ( sem_open() and sem_close()) with unnamed semaphore operations (sem_init() and sem_destroy()) on the same semaphore.

Возвращаемое значение:

0
Успешное завершение. Семафор, описываемый аргументом sem успешно инициализирован.
-1
Возникла ошибка. Код ошибки записан в errno.

Коды ошибок:

EAGAIN
A resource required to initialize the semaphore has been exhausted.
EBUSY
The given semaphore was previously initialized, and has not been destroyed.
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.

Классификация:

POSIX 1003.1 SEM

Точка остановки потока
Нет
Обработчик прерываний
Нет
Обработчик сигналов
Нет
В потоке
Да

Предостережения:

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

Тематические ссылки:

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




Предыдущий раздел: Описание API системной библиотеки