The number of slots currently available; operations acquired without blocking.
The configured concurrency limit — the maximum number of locks that can be held simultaneously.
The number of operations currently waiting for a slot to become available.
Creates a new semaphore with the given concurrency limit.
The maximum number of operations that may run concurrently. Values less than 1 are treated as 1.
const semaphore = new Semaphore(3);
const promises: Promise<void>[] = [];
for (let i = 0; i < 10; ++i) {
const lock = await semaphore.acquire();
const promise = doAsyncTask().finally(lock.release);
promises.push(promise);
}
await Promise.all(promises);
The loop runs 10 asynchronous tasks, but only 3 will ever run simultaneously.
Acquires a lock, blocking until one becomes available. The caller must release the returned lock after the operation completes.
A promise that resolves to a SemaphoreLock once a slot is available.
A concurrency control mechanism that limits the number of asynchronous tasks accessing a shared resource simultaneously.
Use Semaphore.acquire to obtain a SemaphoreLock before starting a task, then call
lock.release()when the task finishes to free the slot for the next waiting operation.The Semaphore.available and Semaphore.waiting getters expose the current state, and Semaphore.size returns the configured concurrency limit.