Hyperlinkv0.8.0-beta.28

TxSemaphore

TxSemaphore.makeconsteffect/TxSemaphore.ts:126
(permits: number): Effect.Effect<TxSemaphore>

Creates a new TxSemaphore with the specified number of permits.

When to use

Use to create a transactional semaphore with a fixed permit capacity.

Example (Creating a semaphore)

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

// Create a semaphore for managing concurrent access to a resource pool
const program = Effect.gen(function*() {
  // Create a semaphore with 3 permits for a connection pool
  const connectionSemaphore = yield* TxSemaphore.make(3)

  // Check initial state
  const available = yield* TxSemaphore.available(connectionSemaphore)
  const capacity = yield* TxSemaphore.capacity(connectionSemaphore)

  yield* Console.log(
    `Created semaphore with ${capacity} permits, ${available} available`
  )
  // Output: "Created semaphore with 3 permits, 3 available"
})
constructorsavailablecapacity
export const make = (permits: number): Effect.Effect<TxSemaphore> =>
  Effect.gen(function*() {
    if (permits < 0) {
      return yield* Effect.die(new Error("Permits must be non-negative"))
    }

    const permitsRef = yield* TxRef.make(permits)
    return makeTxSemaphore(permitsRef, permits)
  }).pipe(Effect.tx)