A semaphore is a mechanism used to prevent race conditions between threads. Semaphores have a value that is shared between threads (and optionally processes). It has two fundamental operations wait
and post
:
wait
— decrements the value atomically. Doesn’t return until the value is greater than 0. The integer value cannot go less than 0.post
— increments the value atomically.
The main use of semaphores is to enforce an order of operations among threads.
Systems programming
In POSIX systems
In POSIX systems, the semaphore API is given in semaphore.h
. It has the following functions, all of which return 0 upon success. It’s a fairly similar API to using mutexes.
sem_init
sem_destroy
sem_wait
sem_trywait
sem_post