@jeppech/semaphore-ts
v1.0.1
Published
A semaphore implementation in TypeScript
Readme
semaphore-ts
A TypeScript semaphore implementation for concurrency control.
Installation
npm install @jeppech/semaphore-tsUsage
Basic Concurrency Control
import { Semaphore } from '@jeppech/semaphore-ts';
const semaphore = new Semaphore(3); // Allow 3 concurrent operations
async function doWork(id: number) {
const release = await semaphore.acquire();
try {
console.log(`Task ${id} started`);
await semaphore.sleep(100);
console.log(`Task ${id} completed`);
} finally {
release();
}
}
await Promise.all([doWork(1), doWork(2), doWork(3), doWork(4)]);
// Only 3 tasks run at a timeBlocking the Semaphore
Temporarily block new acquires:
const semaphore = new Semaphore(2);
const unblock = semaphore.block();
try {
// No new permits can be acquired while blocked
// Existing holders can still work
} finally {
unblock(); // Unblock - waiting acquires will proceed
}Waiting for Unblock
const semaphore = new Semaphore(1);
semaphore.block();
// This will wait until unblocked
await semaphore.wait_for_unblock();API
new Semaphore(max: number)
Create a semaphore with max concurrent permits.
semaphore.acquire(): Promise<Releaser>
Acquire a permit. Returns a promise that resolves to a releaser function.
semaphore.block(): Releaser
Block the semaphore. Returns a releaser to unblock.
semaphore.wait_for_unblock(): Promise<boolean>
Wait until the semaphore is unblocked.
semaphore.sleep(duration: number): Promise<void>
Utility: sleep for duration milliseconds.
