Semaphore
import { Semaphore } from "jsr:@ende/async/unstable-semaphore";class ยท experimental
class SemaphoreA counting semaphore for limiting concurrent access to a resource.
Example: Usage
import { Semaphore } from "@ende/async/unstable-semaphore";
const sem = new Semaphore(2);
{
using _permit = await sem.acquire();
// critical section
} // permit is automatically released when exiting the block
Constructors
constructor
new Semaphore(max: number = 1)Creates a new semaphore with the specified number of permits.
max: number = 1Maximum concurrent permits. Defaults to 1 (mutex).
Methods
acquire
acquire(): Promise<Disposable>Acquires a permit, waiting if none are available.
Returns
A promise that resolves to a Disposable when a permit is acquired.
Example: Usage
import { Semaphore } from "@ende/async/unstable-semaphore";
const sem = new Semaphore(1);
await sem.acquire();
try {
// critical section
} finally {
sem.release();
}
Example: Using using statement
import { Semaphore } from "@ende/async/unstable-semaphore";
const sem = new Semaphore(1);
{
using _permit = await sem.acquire();
// critical section
} // permit is automatically released when exiting the block
tryAcquire
tryAcquire(): Disposable | undefinedTries to acquire a permit without waiting.
Returns
A Disposable if a permit was acquired, undefined otherwise.
Example: Usage
import { Semaphore } from "@ende/async/unstable-semaphore";
const sem = new Semaphore(1);
const permit = sem.tryAcquire();
if (permit) {
using _ = permit;
// critical section
} else {
// resource is busy
}
release
release(): voidReleases a permit, allowing the next waiter to proceed.
Example: Usage
import { Semaphore } from "@ende/async/unstable-semaphore";
const sem = new Semaphore(1);
await sem.acquire();
try {
// critical section
} finally {
sem.release();
}