forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.ts
More file actions
52 lines (44 loc) · 1.07 KB
/
mutex.ts
File metadata and controls
52 lines (44 loc) · 1.07 KB
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
42
43
44
45
46
47
48
49
50
51
52
import setImmediate from '../generic/setImmediate';
/**
* Non-recursive mutex
* @hidden
*/
export default class Mutex {
private _locked: boolean = false;
private _waiters: Function[] = [];
public lock(cb: Function): void {
if (this._locked) {
this._waiters.push(cb);
return;
}
this._locked = true;
cb();
}
public unlock(): void {
if (!this._locked) {
throw new Error('unlock of a non-locked mutex');
}
const next = this._waiters.shift();
// don't unlock - we want to queue up next for the
// _end_ of the current task execution, but we don't
// want it to be called inline with whatever the
// current stack is. This way we still get the nice
// behavior that an unlock immediately followed by a
// lock won't cause starvation.
if (next) {
setImmediate(next);
return;
}
this._locked = false;
}
public tryLock(): boolean {
if (this._locked) {
return false;
}
this._locked = true;
return true;
}
public isLocked(): boolean {
return this._locked;
}
}