A TypeScript semaphore implementation for concurrency control.
npm install @jeppech/semaphore-tsimport { 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 timeTemporarily 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
}const semaphore = new Semaphore(1);
semaphore.block();
// This will wait until unblocked
await semaphore.wait_for_unblock();Create a semaphore with max concurrent permits.
Acquire a permit. Returns a promise that resolves to a releaser function.
Block the semaphore. Returns a releaser to unblock.
Wait until the semaphore is unblocked.
Utility: sleep for duration milliseconds.