Path: blob/main/components/gitpod-protocol/src/util/semaphore.ts
2500 views
/**1* Copyright (c) 2020 Gitpod GmbH. All rights reserved.2* Licensed under the GNU Affero General Public License (AGPL).3* See License.AGPL.txt in the project root for license information.4*/56export class Semaphore {7protected queue: (() => void)[] = [];8protected used: number;910constructor(protected readonly capacity: number) {11if (capacity < 1) {12throw new Error("Capacity cannot be less than 1");13}14}1516public release() {17if (this.used == 0) return;1819const queued = this.queue.shift();20if (queued) {21queued();22}2324this.used--;25}2627public async acquire(): Promise<void> {28this.used++;29if (this.used <= this.capacity) {30return Promise.resolve();31}3233return new Promise<void>((rs, rj) => {34this.queue.push(rs);35});36}37}383940