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.
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