Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-protocol/src/util/semaphore.ts
2500 views
1
/**
2
* Copyright (c) 2020 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
export class Semaphore {
8
protected queue: (() => void)[] = [];
9
protected used: number;
10
11
constructor(protected readonly capacity: number) {
12
if (capacity < 1) {
13
throw new Error("Capacity cannot be less than 1");
14
}
15
}
16
17
public release() {
18
if (this.used == 0) return;
19
20
const queued = this.queue.shift();
21
if (queued) {
22
queued();
23
}
24
25
this.used--;
26
}
27
28
public async acquire(): Promise<void> {
29
this.used++;
30
if (this.used <= this.capacity) {
31
return Promise.resolve();
32
}
33
34
return new Promise<void>((rs, rj) => {
35
this.queue.push(rs);
36
});
37
}
38
}
39
40