Skip to content

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 Semaphore

Constructor

new Semaphore(capacity: number)

Creates a semaphore.

Methods

MethodReturnsDescription
acquire(abortSignal?)Promise<void>Takes a permit, waiting until one is free.
release()voidReturns 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()booleanTakes a permit only if one is free right now.