Semaphores are counters for resources shared between threads. The basic operations on semaphores are: increment the counter atomically, and wait until the counter is non-null and decrement it atomically.
Semaphores have a maximum value past which they cannot be incremented.
The macro SEM_VALUE_MAX
is defined to be this maximum value. In
the GNU C library, SEM_VALUE_MAX
is equal to INT_MAX
(see Range of Type), but it may be much smaller on other systems.
The pthreads library implements POSIX 1003.1b semaphores. These should
not be confused with System V semaphores (ipc
, semctl
and
semop
).
All the semaphore functions and macros are defined in semaphore.h.
sem_init
initializes the semaphore object pointed to by sem. The count associated with the semaphore is set initially to value. The pshared argument indicates whether the semaphore is local to the current process (pshared is zero) or is to be shared between several processes (pshared is not zero).On success
sem_init
returns 0. On failure it returns -1 and sets errno to one of the following values:
EINVAL
- value exceeds the maximal counter value
SEM_VALUE_MAX
ENOSYS
- pshared is not zero. LinuxThreads currently does not support process-shared semaphores. (This will eventually change.)
sem_destroy
destroys a semaphore object, freeing the resources it might hold. If any threads are waiting on the semaphore whensem_destroy
is called, it fails and sets errno toEBUSY
.In the LinuxThreads implementation, no resources are associated with semaphore objects, thus
sem_destroy
actually does nothing except checking that no thread is waiting on the semaphore. This will change when process-shared semaphores are implemented.
sem_wait
suspends the calling thread until the semaphore pointed to by sem has non-zero count. It then atomically decreases the semaphore count.
sem_wait
is a cancellation point. It always returns 0.
sem_trywait
is a non-blocking variant ofsem_wait
. If the semaphore pointed to by sem has non-zero count, the count is atomically decreased andsem_trywait
immediately returns 0. If the semaphore count is zero,sem_trywait
immediately returns -1 and sets errno toEAGAIN
.
sem_post
atomically increases the count of the semaphore pointed to by sem. This function never blocks.On processors supporting atomic compare-and-swap (Intel 486, Pentium and later, Alpha, PowerPC, MIPS II, Motorola 68k, Ultrasparc), the
sem_post
function is can safely be called from signal handlers. This is the only thread synchronization function provided by POSIX threads that is async-signal safe. On the Intel 386 and earlier Sparc chips, the current LinuxThreads implementation ofsem_post
is not async-signal safe, because the hardware does not support the required atomic operations.
sem_post
always succeeds and returns 0, unless the semaphore count would exceedSEM_VALUE_MAX
after being incremented. In that casesem_post
returns -1 and sets errno toEINVAL
. The semaphore count is left unchanged.