Hyperlinkv0.8.0-beta.28

TxSemaphore

TxSemaphore.acquireconsteffect/TxSemaphore.ts:241
(self: TxSemaphore): Effect.Effect<void>

Acquires a single permit from the semaphore. If no permits are available, the effect will block until one becomes available.

When to use

Use to manually acquire one permit transactionally, waiting until one is available.

Example (Acquiring a permit)

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

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

  yield* Console.log("Acquiring first permit...")
  yield* TxSemaphore.acquire(semaphore)
  yield* Console.log("First permit acquired")

  yield* Console.log("Acquiring second permit...")
  yield* TxSemaphore.acquire(semaphore)
  yield* Console.log("Second permit acquired")

  const available = yield* TxSemaphore.available(semaphore)
  yield* Console.log(`Available permits: ${available}`) // 0
})
export const acquire = (self: TxSemaphore): Effect.Effect<void> =>
  Effect.gen(function*() {
    const permits = yield* TxRef.get(self.permitsRef)
    if (permits <= 0) {
      return yield* Effect.txRetry
    }
    yield* TxRef.set(self.permitsRef, permits - 1)
  }).pipe(Effect.tx)
Referenced by 2 symbols