We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 8b34e30 commit ce9a3fdCopy full SHA for ce9a3fd
1 file changed
src/concurrency.ts
@@ -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
28
29
30
+ this.#count += 1;
31
32
+}
0 commit comments