aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/vendor/async-mutex/mutex.ts
blob: 9fe6e7a2331ba8abfe1b255b3ba2a6c8d185818a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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;