AniUI Academy

Build a counting semaphore

hardAsync & Promises+350 XPPractice

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 max holders at any time.
  • Resolve acquire() immediately while permits are free.
  • Hand a released permit to waiters in FIFO order.
  • Resolve with a release function rather than a plain value.
  • Make release idempotent: extra calls do nothing.

Notes

  • Make release idempotent with a closed-over released flag — 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.

Try it yourself
Loading playground...
5 tests · +350 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.