POSIX Semaphore¶
POSIX semaphores provide counting-based synchronization between threads or processes.
They are often used with shared memory to coordinate producer/consumer behavior.
What Problem It Solves¶
Use POSIX semaphores when processes need to wait for resource availability or signal state changes.
Typical use cases:
- producer/consumer queues
- shared memory ring buffers
- resource counting
- process-to-process synchronization
Core Concepts¶
| Concept | Description |
|---|---|
sem_init() |
Initializes an unnamed semaphore |
sem_wait() |
Decrements or waits until the semaphore is available |
sem_post() |
Increments and wakes one waiter |
sem_destroy() |
Destroys an unnamed semaphore |
pshared |
Enables process-shared usage when non-zero |
Shared Memory Queue Pattern¶
A common design uses:
- one mutex for ring buffer metadata protection
- one semaphore for available items
- one semaphore for available slots
Producer:
wait(empty_slots)
lock(mutex)
write item
unlock(mutex)
post(used_slots)
Consumer:
wait(used_slots)
lock(mutex)
read item
unlock(mutex)
post(empty_slots)
Common Pitfalls¶
Warning
For process-shared unnamed semaphores, the semaphore object must live in shared memory and pshared must be non-zero.
Note
A semaphore is not a replacement for a mutex when shared data structure consistency must be protected.