-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
60 lines (53 loc) · 1.34 KB
/
mod.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
import { FIFOQueue } from "./FIFOQueue.ts";
type Task<T> = () => Promise<T>;
class Deffered<T> {
constructor() {
this.promise = new Promise((resolve, reject) => {
this.reject = reject;
this.resolve = resolve;
});
}
resolve!: (value: T | PromiseLike<T>) => void;
reject!: (value: T | PromiseLike<T>) => void;
promise: Promise<T>;
}
export class Pool {
private workingCount = 0;
private waitQueue: FIFOQueue<Deffered<void>> = new FIFOQueue();
constructor(private size: number) {
if (size < 1) {
throw new Error("Pool size must be greater than 0");
}
}
public async exec<T>(task: Task<T>): Promise<T> {
if (this.workingCount >= this.size) {
await this.waitForAvailability();
}
this.workingCount++;
try {
return await task();
} finally {
this.workingCount--;
if (this.workingCount < this.size) {
this.releaseFirstWaiter();
}
}
}
private releaseFirstWaiter() {
this.waitQueue.dequeue()?.resolve();
}
private async waitForAvailability() {
const wait = new Deffered<void>();
this.waitQueue.enqueue(wait);
await wait.promise;
}
public getSize(): number {
return this.size;
}
public getWorkingCount(): number {
return this.workingCount;
}
public getPendingCount(): number {
return this.waitQueue.getSize();
}
}