Codacoda
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

INITIALSemaphore(2)0/2Connection Poolconn1conn2Thread 1idleThread 2idleThread 3idle
Speed:1x
Three threads need access to a connection pool. A semaphore allows at most 2 concurrent users.Step 1 / 7

Implementation

Output

Click "Run Code" to see output...