Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

761 B
Raw Blame
export class Semaphore {
    private waiting: Array<() => void> = []

    constructor(private permits: number) {}

    private async acquire(): Promise<void> {
        if (this.permits > 0) {
            this.permits--
            return
        }
        return new Promise<void>((resolve) => this.waiting.push(resolve))
    }

    private release(): void {
        if (this.waiting.length > 0) {
            const next = this.waiting.shift()
            if (next) {
                next()
            }
        } else {
            this.permits++
        }
    }

    async run<T>(func: () => Promise<T>): Promise<T> {
        await this.acquire()
        try {
            return await func()
        } finally {
            this.release()
        }
    }
}