-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemaphore.ts
63 lines (50 loc) · 1.11 KB
/
semaphore.ts
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
53
54
55
56
57
58
59
60
61
62
63
class Lock {
#released = false;
#onRelease: () => void;
constructor(onRelease: () => void) {
this.#onRelease = onRelease;
this.release = this.release.bind(this);
}
release(): void {
if (this.#released) return;
this.#released = true;
this.#onRelease();
}
}
export class Semaphore {
readonly #size: number;
#available: number;
#waiting: (() => void)[] = [];
#next(): void {
if (this.#available <= 0) return;
this.#waiting.shift()?.();
}
get size(): number {
return this.#size;
}
get available(): number {
return this.#available;
}
get waiting(): number {
return this.#waiting.length;
}
constructor(size: number) {
this.#size = Math.max(1, Math.trunc(size));
this.#available = this.#size;
this.acquire = this.acquire.bind(this);
}
acquire(): Promise<Lock> {
return new Promise((resolve) => {
this.#waiting.push(() => {
this.#available -= 1;
resolve(
new Lock(() => {
this.#available += 1;
this.#next();
}),
);
});
this.#next();
});
}
}