Skip to content

Commit ce9a3fd

Browse files
committed
feat: add counting semaphore
1 parent 8b34e30 commit ce9a3fd

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

src/concurrency.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
export class CountingSemaphore {
2+
#count: number;
3+
readonly #waiters: (() => void)[] = [];
4+
5+
constructor(count: number) {
6+
if (count < 1) {
7+
throw new Error("Semaphore count must be at least 1");
8+
}
9+
this.#count = count;
10+
}
11+
12+
async acquire(): Promise<void> {
13+
if (this.#count > 0) {
14+
this.#count -= 1;
15+
return;
16+
}
17+
18+
await new Promise<void>((resolve) => {
19+
this.#waiters.push(resolve);
20+
});
21+
}
22+
23+
release(): void {
24+
const nextResolve = this.#waiters.shift();
25+
if (nextResolve !== undefined) {
26+
nextResolve();
27+
return;
28+
}
29+
30+
this.#count += 1;
31+
}
32+
}

0 commit comments

Comments
 (0)