Semaphore
A counting semaphore for async functions.
Each Semaphore.acquire takes a permit, or waits until one is released. Each Semaphore.release hands its permit to the longest-waiting acquirer, first in first out, or returns it to the pool.
Import:
import { Semaphore } from '@mnaoumov/typescript-lib/semaphore';Example:
const semaphore = new Semaphore(3);
await Promise.all(files.map((file) => semaphore.runExclusive(() => processFile(file))));Signature:
export class SemaphoreConstructor
new Semaphore(capacity: number)Creates a semaphore.
Methods
| Method | Returns | Description |
|---|---|---|
| acquire(abortSignal?) | Promise<void> | Takes a permit, waiting until one is free. |
| release() | void | Returns a permit, handing it to the longest-waiting acquirer if there is one. |
| runExclusive(operation, abortSignal?) | Promise<T> | Runs a function while holding a permit, releasing it when the function settles. |
| tryAcquire() | boolean | Takes a permit only if one is free right now. |