Back to Academy
concurrency
Semaphores
A semaphore is a synchronization primitive that controls access to a shared resource through a counter. Unlike a mutex which allows only one accessor, a semaphore permits up to N concurrent accessors, making it ideal for limiting parallelism. When the counter reaches zero, subsequent requesters must wait until a slot is released. Semaphores are widely used to implement connection pools, rate limiters, and bounded resource access.
Use Cases
- •Limiting the number of concurrent database connections in a pool
- •Throttling API calls to respect rate limits
- •Controlling how many files can be processed simultaneously
- •Managing bounded buffer access in producer-consumer systems
Visualization
Implementation
Output
Click "Run Code" to see output...