Skip to content

Semaphore

Defined in: packages/async/src/synchro/semaphore.ts:19

A general/counting strong semaphore implementation.

A semaphore maintains a set of permits. Each acquire call blocks if necessary until a permit is available, and then takes it. Each release call adds a permit, potentially releasing a blocking acquirer.

The semaphore is initialized with a given number of permits. The number of permits can be increased up to a maximum value.

The order of permit acquisition is guaranteed to be FIFO.

Usage: Only meaningful when the critical section contains at least one await — synchronous operations cannot be interleaved in JS’s single-threaded model.

new Semaphore(maxValue, initialValue?): Semaphore

Defined in: packages/async/src/synchro/semaphore.ts:32

Creates a new semaphore with the given initial number of permits and maximum number of permits.

number

The maximum number of permits.

number

The initial number of permits available. Defaults to maxValue.

Semaphore

get value(): number

Defined in: packages/async/src/synchro/semaphore.ts:53

The current number of available permits.

number

The current number of available permits.

acquire(count?, signal?): Promise<void>

Defined in: packages/async/src/synchro/semaphore.ts:92

Acquires a permit from the semaphore, waiting if necessary until one is available.

number = 1

AbortSignal | null

An optional AbortSignal to cancel the acquire operation.

Promise<void>

A promise that resolves to a lease when the permits are acquired.


getMaxValue(): number

Defined in: packages/async/src/synchro/semaphore.ts:62

The maximum number of permits.

number

The maximum number of permits.


release(count?): void

Defined in: packages/async/src/synchro/semaphore.ts:114

Releases permits back to the semaphore.

Any pending acquisitions will be processed asynchronously after this call.

number = 1

The number of permits to release.

void


tryAcquire(count?): boolean

Defined in: packages/async/src/synchro/semaphore.ts:72

Tries to acquire a permit from the semaphore immediately, without waiting.

number = 1

The number of permits to acquire.

boolean

true if the permits were acquired, false otherwise.