MCPcopy Create free account
hub / github.com/Effect-TS/effect / acquireWrite

Function acquireWrite

packages/effect/src/TxReentrantLock.ts:203–239  ·  view source on GitHub ↗
(self: TxReentrantLock)

Source from the content-addressed store, hash-verified

201 * @since 2.0.0
202 */
203export const acquireWrite = (self: TxReentrantLock): Effect.Effect<number> =>
204 Effect.withFiber((fiber) =>
205 Effect.gen(function*() {
206 const state = yield* TxRef.get(self.stateRef)
207 const fiberId = fiber.id
208
209 // If another fiber holds the write lock, retry
210 if (Option.isSome(state.writer) && state.writer.value[0] !== fiberId) {
211 return yield* Effect.txRetry
212 }
213
214 // If other fibers hold read locks, retry
215 for (const [readerId] of state.readers) {
216 if (readerId !== fiberId && Option.getOrElse(HashMap.get(state.readers, readerId), () => 0) > 0) {
217 return yield* Effect.txRetry
218 }
219 }
220
221 // Grant write lock
222 if (Option.isSome(state.writer)) {
223 // Reentrant: increment write count
224 const newCount = state.writer.value[1] + 1
225 yield* TxRef.set(self.stateRef, {
226 ...state,
227 writer: Option.some([fiberId, newCount] as const)
228 })
229 return newCount
230 }
231
232 // First write lock acquisition
233 yield* TxRef.set(self.stateRef, {
234 ...state,
235 writer: Option.some([fiberId, 1] as const)
236 })
237 return 1
238 }).pipe(Effect.tx)
239 )
240
241/**
242 * Releases one read lock held by the current fiber.

Callers 2

writeLockFunction · 0.85
TxReentrantLock.tsFile · 0.85

Calls 4

someMethod · 0.80
pipeMethod · 0.65
getMethod · 0.65
setMethod · 0.65

Tested by

no test coverage detected