1 |
class Mutex { |
1✔ |
2 |
private _locked: boolean;
|
1✔ |
3 |
private readonly _queue: (() => void)[]; |
1✔ |
4 |
constructor() { |
|
5 |
this._locked = false; |
26✔ |
6 |
this._queue = [];
|
26✔ |
7 |
} |
26✔ |
8 |
|
1✔ |
9 |
lock(fn: () => void) {
|
|
10 |
if (this._locked) { |
|
11 |
this._queue.push(fn);
|
319✔ |
12 |
return;
|
319✔ |
13 |
} |
319✔ |
14 |
|
|
15 |
this._locked = true; |
632✔ |
16 |
fn(); |
632✔ |
17 |
} |
632✔ |
18 |
|
1✔ |
19 |
unlock() { |
|
20 |
if (!this._locked) return; |
|
21 |
|
950✔ |
22 |
const next = this._queue.shift(); |
950✔ |
23 |
|
950✔ |
24 |
if (next) {
|
|
25 |
next(); |
319✔ |
26 |
} else {
|
|
27 |
this._locked = false; |
631✔ |
28 |
} |
631✔ |
29 |
} |
950✔ |
30 |
} |
1✔ |
31 |
|
1✔ |
32 |
export default Mutex; |
1✔ |