1 |
'use strict';
|
|
2 |
|
|
3 |
class Mutex {
|
|
4 |
constructor() { |
|
5 |
this._locked = false; |
24✔ |
6 |
this._queue = [];
|
24✔ |
7 |
} |
|
8 |
|
|
9 |
lock(fn) { |
|
10 |
if (this._locked) { |
|
11 |
this._queue.push(fn);
|
310✔ |
12 |
return;
|
310✔ |
13 |
} |
|
14 |
|
|
15 |
this._locked = true; |
605✔ |
16 |
fn(); |
605✔ |
17 |
} |
|
18 |
|
|
19 |
unlock() { |
|
20 |
if (!this._locked) return; |
|
21 |
|
|
22 |
const next = this._queue.shift();
|
914✔ |
23 |
|
|
24 |
if (next) {
|
|
25 |
next(); |
310✔ |
26 |
} else {
|
|
27 |
this._locked = false; |
604✔ |
28 |
} |
|
29 |
} |
|
30 |
} |
|
31 |
|
|
32 |
module.exports = Mutex; |
1✔ |