Build a counting semaphore
A pool works when you already have the full list of tasks. When work arrives over time — a user clicking upload repeatedly — you need a permit you can acquire from anywhere and release when done.
Implement a class Semaphore. new Semaphore(max) allows max holders at once. acquire() returns a promise; it resolves immediately if fewer than max permits are held, and otherwise waits until one is released. It resolves with a release function that gives the permit back and hands it to the longest-waiting caller, in first-in-first-out order. Calling a release function more than once has no effect beyond the first call, so a double release can never let an extra caller through.
Arguments
maxnumber- Constructor argument — the maximum number of concurrent permit holders.
Returns
Promise<() => void> — acquire() returns a promise that resolves with a release function. Call it to hand the permit back.
Examples
const sem = new Semaphore(3);
async function upload(file) {
const release = await sem.acquire();
try {
return await uploadToS3(file);
} finally {
release();
}
}
// At most three uploads run concurrently, no matter how many callers.Permit-based concurrency control for work that arrives over time.
What it has to do
- Allow at most
maxholders at any time. - Resolve
acquire()immediately while permits are free. - Hand a released permit to waiters in FIFO order.
- Resolve with a
releasefunction rather than a plain value. - Make
releaseidempotent: extra calls do nothing.
Notes
- Make
releaseidempotent with a closed-overreleasedflag — a double release can otherwise let an extra holder through and silently break the invariant. - Hand permits to waiters in FIFO order (
waiting.shift()), not LIFO — callers assume fairness.
Stuck? The javascript course covers everything this challenge needs.
- 1.allows up to max holders at once
- 2.resolves immediately while permits are free
- 3.hands the permit to waiters in FIFO order
- 4.ignores a repeated release
- 5.a waiter stays pending until a permit is released
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.