UNPKG

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