Hyperlinkv0.8.0-beta.28

TxSemaphore

TxSemaphore.withPermitScopedconsteffect/TxSemaphore.ts:669
(self: TxSemaphore): Effect.Effect<void, never, Scope.Scope>

Acquires a single permit from the semaphore in a scoped manner. The permit will be automatically released when the scope is closed, even if effects within the scope fail or are interrupted.

When to use

Use to acquire one transactional permit for the lifetime of the current scope.

Details

The permit acquisition and release operations use atomic semantics to ensure proper resource management with Effect's scoped operations.

Example (Acquiring a scoped permit)

import { Console, Effect, TxSemaphore } from "effect"

const program = Effect.gen(function*() {
  const semaphore = yield* TxSemaphore.make(3)

  yield* Effect.scoped(
    Effect.gen(function*() {
      // Acquire permit for the duration of this scope
      yield* TxSemaphore.withPermitScoped(semaphore)
      yield* Console.log("Permit acquired for scope")

      // Do work within the scope
      yield* Effect.sleep("500 millis")
      yield* Console.log("Work completed")

      // Permit will be automatically released when scope closes
    })
  )

  yield* Console.log("Scope closed, permit released")
})
export const withPermitScoped = (self: TxSemaphore): Effect.Effect<void, never, Scope.Scope> =>
  Effect.acquireRelease(
    acquire(self),
    () => release(self)
  )