From 80d0342636056bc839517b64fd11708abea70237 Mon Sep 17 00:00:00 2001 From: memdmp Date: Wed, 20 Aug 2025 12:46:01 +0000 Subject: feat: locks :3 --- src/lib/vendor/async-mutex/mutex.ts | 41 +++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/lib/vendor/async-mutex/mutex.ts (limited to 'src/lib/vendor/async-mutex/mutex.ts') diff --git a/src/lib/vendor/async-mutex/mutex.ts b/src/lib/vendor/async-mutex/mutex.ts new file mode 100644 index 0000000..9fe6e7a --- /dev/null +++ b/src/lib/vendor/async-mutex/mutex.ts @@ -0,0 +1,41 @@ +import type { MutexInterface } from './interface'; +import Semaphore from './semaphore'; + +class Mutex implements MutexInterface { + constructor(cancelError?: Error) { + this._semaphore = new Semaphore(1, cancelError); + } + + async acquire(priority = 0): Promise { + const [, releaser] = await this._semaphore.acquire(1, priority); + + return releaser; + } + + runExclusive( + callback: MutexInterface.Worker, + priority = 0 + ): Promise { + return this._semaphore.runExclusive(() => callback(), 1, priority); + } + + isLocked(): boolean { + return this._semaphore.isLocked(); + } + + waitForUnlock(priority = 0): Promise { + return this._semaphore.waitForUnlock(1, priority); + } + + release(): void { + if (this._semaphore.isLocked()) this._semaphore.release(); + } + + cancel(): void { + return this._semaphore.cancel(); + } + + private _semaphore: Semaphore; +} + +export default Mutex; -- cgit v1.2.3