"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Lock = void 0;
class Lock {
    constructor() {
        this.queue = [];
        this.acquired = false;
    }
    async acquire() {
        if (!this.acquired) {
            this.acquired = true;
        }
        else {
            return new Promise((resolve, _) => {
                this.queue.push(resolve);
            });
        }
    }
    async release() {
        if (this.queue.length === 0 && this.acquired) {
            this.acquired = false;
            return;
        }
        const continuation = this.queue.shift();
        return new Promise((res) => {
            continuation();
            res();
        });
    }
    async critical(task) {
        await this.acquire();
        try {
            return await task();
        }
        finally {
            await this.release();
        }
    }
}
exports.Lock = Lock;
//# sourceMappingURL=lock.js.map