Skip to main content

interface Semaphore

A Semaphore is a generalized version of a Mutex, allowing boundaries on the amount of concurrent processes that can have simultaneous access to a shared resource. The semaphore is weighted, meaning that the semaphore has a maximum size/capacity available for the shared resources. When acquiring the resource, a weight can be provided allowing more intensive tasks to acquire a larger share of the shared resource, preventing too many other tasks from also acquiring the resource.

Companion namespace: Semaphore

Implemented by: Mutex

Properties​

maxSize​

The maximum simultaneous "weight" that the semaphore allows access to for the shared resource.

Definition​

readonly maxSize: number;

Methods​

acquire​

Request access to a shared resource with the given weight. Blocks if the semaphore has insufficient capacity until enough weight has been released. Resolves when the semaphore has enough capacity for the operation.

Definition​

acquire(weight?: number, options?: {
    signal?: AbortSignal | undefined;
    timeoutMs?: number | undefined;
  }): Promise<void>;

Parameters​

NameTypeDescription
weightnumber(default: 1) the weight of the operation to be performed
options{
    signal?: AbortSignal | undefined;
    timeoutMs?: number | undefined;
  }

canAcquire​

Returns true if the semaphore will directly give access to the shared resource for the given weight when requested.

Definition​

canAcquire(weight?: number): boolean;

Parameters​

NameTypeDescription
weightnumber(default: 1) the desired weight for access request

release​

Release obtained capacity from the semaphore to allow potential other blocked processes to access the resource.

Definition​

release(weight?: number): void;

Parameters​

NameTypeDescription
weightnumber(default: 1) the amount of weight to release