diff options
feat: locks :3
Diffstat (limited to 'src/lib/vendor/async-mutex/mutex.ts')
| -rw-r--r-- | src/lib/vendor/async-mutex/mutex.ts | 41 |
1 files changed, 41 insertions, 0 deletions
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<MutexInterface.Releaser> { + const [, releaser] = await this._semaphore.acquire(1, priority); + + return releaser; + } + + runExclusive<T>( + callback: MutexInterface.Worker<T>, + priority = 0 + ): Promise<T> { + return this._semaphore.runExclusive(() => callback(), 1, priority); + } + + isLocked(): boolean { + return this._semaphore.isLocked(); + } + + waitForUnlock(priority = 0): Promise<void> { + 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; |