Hyperlinkv0.8.0-beta.28

TxReentrantLock

TxReentrantLock.acquireReadconsteffect/TxReentrantLock.ts:141
(self: TxReentrantLock): Effect.Effect<number>

Acquires a read lock. Blocks if another fiber holds the write lock. If the current fiber already holds the write lock, the read lock is granted (reentrancy). Returns the current number of read locks held by this fiber.

Example (Acquiring a read lock)

import { Effect, TxReentrantLock } from "effect"

const program = Effect.gen(function*() {
  const lock = yield* TxReentrantLock.make()
  const count = yield* TxReentrantLock.acquireRead(lock)
  console.log(count) // 1
  yield* TxReentrantLock.releaseRead(lock)
})
mutations
export const acquireRead = (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
      }

      // Grant read lock
      const currentCount = Option.getOrElse(HashMap.get(state.readers, fiberId), () => 0)
      const newCount = currentCount + 1
      yield* TxRef.set(self.stateRef, {
        ...state,
        readers: HashMap.set(state.readers, fiberId, newCount)
      })
      return newCount
    }).pipe(Effect.tx)
  )
Referenced by 2 symbols