UNPKG

@apiratorjs/locking

Version:

A lightweight library providing both local and distributed locking primitives (mutexes, semaphores, and read-write locks) for managing concurrency in Node.js.

38 lines 2.3 kB
import { AcquireParams, ExclusiveCallback, IReadWriteLock, IReleaser, ReadLockToken, RWLockConstructorProps, WriteLockToken } from "./types"; /** * ReadWriteLock (short for Read-Write Lock) is a synchronization mechanism that allows multiple threads to read from a resource simultaneously, * but prohibits writing if someone is reading, and vice versa: if writing is in progress, no one can read or write. * * The main principles of ReadWriteLock operation: * • Multiple threads can read simultaneously if there is no writing. * • Only one thread can write, and during writing, no reads are allowed. * • This improves performance with a large number of read operations and infrequent writes. * * This implementation handles locks in the order they are requested: * • Readers can acquire locks concurrently as long as no writer is active * • Writers must wait for all active readers to release their locks before acquiring the write lock * • New readers can acquire locks even if writers are waiting, as long as no writer is currently active * * Explanation in simple terms: * 1. There are multiple threads reading data — that's fine, they can do it simultaneously. * 2. At some point, a thread wants to write — it calls acquireWrite(): * • It cannot write while others are reading, so it queues and waits. * 3. Meanwhile, new read requests can still be granted while writers are waiting. */ export declare class ReadWriteLock implements IReadWriteLock { private _readSemaphore; private _writeSemaphore; constructor(props?: RWLockConstructorProps); maxReaders(): Promise<number>; activeReaders(): Promise<number>; acquireRead(params?: AcquireParams): Promise<IReleaser<ReadLockToken>>; acquireWrite(params?: AcquireParams): Promise<IReleaser<WriteLockToken>>; cancelAll(errMessage?: string): Promise<void>; withReadLock<T>(fn: ExclusiveCallback<T>): Promise<T>; withReadLock<T>(params: AcquireParams, fn: ExclusiveCallback<T>): Promise<T>; withWriteLock<T>(fn: ExclusiveCallback<T>): Promise<T>; withWriteLock<T>(params: AcquireParams, fn: ExclusiveCallback<T>): Promise<T>; isWriteLocked(): Promise<boolean>; isReadLocked(): Promise<boolean>; } //# sourceMappingURL=read-write-lock.d.ts.map