UNPKG

mutex-ts

Version:

This package provides two classes for managing locks: `Mutex` and `MutexRW`. These locks can be used to control access to critical sections in a multi-threaded or asynchronous environment.

96 lines (95 loc) 3.01 kB
/** * A simple mutual exclusion lock. It allows you to obtain and release a lock, * ensuring that only one task can access a critical section at a time. */ export declare class Mutex { private m_lastPromise; /** * Acquire lock * @param [bypass=false] option to skip lock acquisition */ obtain(bypass?: boolean): Promise<() => void>; /** * Creates a lock object that can be used with the `using` statement. * The `using` statement ensures that the lock is released even if an error occurs within the block. * * @returns An object with a `Symbol.dispose` method that releases the lock when called. * * @example * ```typescript * async function main() { * const mutex = new Mutex(); * { * using _ = await mutex.lock(); * // Critical section * // The lock is automatically released when the block exits * } * } * ``` */ lock(bypass?: boolean): Promise<{ [Symbol.dispose]: () => void; }>; } /** * A mutual exclusion lock that supports multiple readers or a single writer. * Readers can obtain a read lock simultaneously, but writers must wait until all readers release the lock. * It helps in scenarios where you want to optimize concurrent read operations but ensure exclusive write access. */ export declare class MutexRW { private m_nextRWPromise; private m_lastRWPromise; private m_lastROPromise; private roAccessCnt; private rwAccess; /** * Acquire read lock */ obtainRO(): Promise<() => void>; /** * Creates a read lock object that can be used with the `using` statement. * The `using` statement ensures that the lock is released even if an error occurs within the block. * * @returns An object with a `Symbol.dispose` method that releases the lock when called. * * @example * ```typescript * async function main() { * const mutex = new MutexRW(); * { * using _ = await mutex.lockRO(); * // Critical section * // The lock is automatically released when the block exits * } * } * ``` */ lockRO(): Promise<{ [Symbol.dispose]: () => void; }>; /** * Acquire write lock */ obtainRW(): Promise<() => void>; /** * Creates a write lock object that can be used with the `using` statement. * The `using` statement ensures that the lock is released even if an error occurs within the block. * * @returns An object with a `Symbol.dispose` method that releases the lock when called. * * @example * ```typescript * async function main() { * const mutex = new MutexRW(); * { * using _ = await mutex.lockRW(); * // Critical section * // The lock is automatically released when the block exits * } * } * ``` */ lockRW(): Promise<{ [Symbol.dispose]: () => void; }>; }