Hyperlinkv0.8.0-beta.28

TxReentrantLock

TxReentrantLock.acquireWriteconsteffect/TxReentrantLock.ts:195
(self: TxReentrantLock): Effect.Effect<number>

Acquires the write lock for the current fiber.

When to use

Use to enter an exclusive section manually when withWriteLock is not the right shape.

Details

Blocks if any other fiber holds a read or write lock. If the current fiber already holds the write lock, the count is incremented. If the current fiber holds a read lock, the write lock is granted as an upgrade.

Returns the current number of write locks held by this fiber.

Example (Acquiring a write lock)

import { Effect, TxReentrantLock } from "effect"

const program = Effect.gen(function*() {
  const lock = yield* TxReentrantLock.make()
  const count = yield* TxReentrantLock.acquireWrite(lock)
  console.log(count) // 1
  yield* TxReentrantLock.releaseWrite(lock)
})
mutations
export const acquireWrite = (self: TxReentrantLock): Effect.Effect<number> =>
  Effect.withFiber((fiber) =>
    Effect.gen(function*() {
      const state = yield* TxRef.get(self.stateRef)
      const fiberId = fiber.id

      // If another fiber holds the write lock, retry
      if (Option.isSome(state.writer) && state.writer.value[0] !== fiberId) {
        return yield* Effect.txRetry
      }

      // If other fibers hold read locks, retry
      for (const [readerId] of state.readers) {
        if (readerId !== fiberId && Option.getOrElse(HashMap.get(state.readers, readerId), () => 0) > 0) {
          return yield* Effect.txRetry
        }
      }

      // Grant write lock
      if (Option.isSome(state.writer)) {
        // Reentrant: increment write count
        const newCount = state.writer.value[1] + 1
        yield* TxRef.set(self.stateRef, {
          ...state,
          writer: Option.some([fiberId, newCount] as const)
        })
        return newCount
      }

      // First write lock acquisition
      yield* TxRef.set(self.stateRef, {
        ...state,
        writer: Option.some([fiberId, 1] as const)
      })
      return 1
    }).pipe(Effect.tx)
  )
Referenced by 2 symbols