-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsemaphore.ts
50 lines (45 loc) · 1.03 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
export class Semaphore {
private tasks: (() => void)[] = [];
count: number;
constructor(count: number) {
this.count = count;
}
private schedule() {
if (this.count > 0 && this.tasks.length > 0) {
this.count--;
const next = this.tasks.shift();
if (next === undefined) {
throw "Unexpected undefined value in tasks list";
}
next();
}
}
/** returns current scheduled tasks length */
get length(): number {
return this.tasks.length;
}
public acquire() {
return new Promise<() => void>((resolve) => {
const task = () => {
let released = false;
resolve(() => {
if (!released) {
released = true;
this.count++;
this.schedule();
}
});
};
this.tasks.push(task);
queueMicrotask(this.schedule.bind(this));
});
}
public async use<T>(fn: () => Promise<T>) {
const release = await this.acquire();
try {
return await fn();
} finally {
release();
}
}
}