A semaphore is a synchronization mechanism used to manage access to a shared resource. In Effect, semaphores help control resource access or coordinate tasks within asynchronous, concurrent operations.
A semaphore acts as a generalized mutex, allowing a set number of permits to be held and released concurrently. Permits act like tickets, giving tasks or fibers controlled access to a shared resource. When no permits are available, tasks trying to acquire one will wait until a permit is released.
Creating a Semaphore
The Effect.makeSemaphore function initializes a semaphore with a specified number of permits.
Each permit allows one task to access a resource or perform an operation concurrently, and multiple permits enable a configurable level of concurrency.
Example (Creating a Semaphore with 3 Permits)
withPermits
The withPermits method lets you specify the number of permits required to run an effect. Once the specified permits are available, it runs the effect, automatically releasing the permits when the task completes.
Example (Forcing Sequential Task Execution with a One-Permit Semaphore)
In this example, three tasks are started concurrently, but they run sequentially because the one-permit semaphore only allows one task to proceed at a time.
Example (Using Multiple Permits to Control Concurrent Task Execution)
In this example, we create a semaphore with five permits and use withPermits(n) to allocate a different number of permits for each task: