Semaphore
Semaphores are synchronization primitives used to control access to shared resources in concurrent programming. They maintain a counter that represents the number of available resources.
Main types:
- Binary semaphores: Counter values are 0 or 1 (functioning like mutexes)
- Counting semaphores: Counter can have arbitrary non-negative values
Core operations:
wait/P/down
: Decrement counter if it's > 0, otherwise blocks until it cansignal/V/up
: Increment counter, potentially unblocking waiting processes
Basic Semaphore API
typedef struct { int value; /* ... */ } semaphore; void sem_init(semaphore *sem, int value); void sem_wait(semaphore *sem); int sem_trywait(semaphore *sem); // non-blocking void sem_post(semaphore *sem); int sem_value(semaphore *sem, int *sval); void sem_destroy(semaphore *sem);