Semaphore is a concurrency primitive that controls access to a shared permit pool. It’s useful for limiting the number of concurrent operations or coordinating access to resources.
Overview
Semaphores provide:- Permit-based control: Limit concurrent access with permits
- Blocking operations: Tasks wait until permits are available
- FIFO fairness: First-in, first-out ordering for waiting tasks
- Resize support: Dynamically adjust available permits
Basic Usage
Types
Semaphore
Creating Semaphores
make
makeUnsafe
Using Permits
withPermits
withPermit
withPermits(1).
withPermitsIfAvailable
Option.none if permits are not available.
Manual Permit Management
take
release
releaseAll
Resizing
resize
Common Patterns
Rate Limiting
Control the rate of concurrent operations:Resource Pool
Manage access to a limited resource pool:Weighted Permits
Different tasks can require different numbers of permits:Partitioned Semaphores
Partitioned
Partitioned semaphore controls access to a shared permit pool while tracking waiters by partition key. Waiting permits are distributed across partitions in round-robin order.
makePartitioned
Partitioned semaphore.
makePartitionedUnsafe
Partitioned semaphore.
