Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Async semaphore with n permits in JavaScript

29 A semaphore with n permits

hard

Write a semaphore: acquire() resolves when a permit is free, release() gives one back. Run five jobs through one with two permits and prove the peak concurrency was two. Check what release does when someone is already waiting.

Stuck? Three hints, smallest first
  1. 1. A count of free permits and a queue of parked resolve functions is the whole state.
  2. 2. release() should hand the permit directly to the next waiter rather than returning it to the pool.
  3. 3. A use(fn) wrapper with try/finally is what callers should actually touch.

The answer

function createSemaphore(permits) {
  let free = permits;
  const waiting = [];
  return {
    get free() { return free; },
    get queued() { return waiting.length; },
    acquire() {
      if (free > 0) { free--; return Promise.resolve(); }
      return new Promise((resolve) => waiting.push(resolve));
    },
    release() {
      const next = waiting.shift();
      if (next) next();               // handed straight on: the count never moves
      else free++;
    },
    async use(fn) {
      await this.acquire();
      try { return await fn(); } finally { this.release(); }
    },
  };
}

const sem = createSemaphore(2);
let active = 0;
let peak = 0;
const job = (n) =>
  sem.use(async () => {
    active++;
    peak = Math.max(peak, active);
    await Promise.resolve();
    await Promise.resolve();
    active--;
    return n;
  });
const out = await Promise.all([1, 2, 3, 4, 5].map(job));

const one = createSemaphore(1);
let mutexPeak = 0;
let mutexActive = 0;
await Promise.all([1, 2, 3].map(() =>
  one.use(async () => {
    mutexActive++;
    mutexPeak = Math.max(mutexPeak, mutexActive);
    await Promise.resolve();
    mutexActive--;
  })
));

const queueing = createSemaphore(1);
queueing.acquire();
queueing.acquire();
const queuedState = [queueing.free, queueing.queued];

const handoff = createSemaphore(1);
await handoff.acquire();
const waiter = handoff.acquire();
handoff.release();
const duringHandoff = handoff.free;
await waiter;

const afterThrow = await (async () => {
  const s = createSemaphore(1);
  await s.use(async () => { throw new Error('x'); }).catch(() => {});
  return s.free;
})();

console.log('results:', out, ' peak:', peak, 'of 2');
console.log('permits of 1 behaves as a mutex, peak:', mutexPeak);
console.log('one permit, two acquirers:', queuedState);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('every job ran', out, [1, 2, 3, 4, 5]);
test('never more than two at once', peak, 2);
test('all permits are back afterwards', sem.free, 2);
test('and nobody is left queued', sem.queued, 0);
test('a semaphore of one permit is a mutex', mutexPeak, 1);
test('acquiring beyond the permits queues rather than failing', queuedState, [0, 1]);
test('release hands the permit straight to the waiter, so the count stays at zero', [duringHandoff, handoff.free], [0, 0]);
test('a throw inside use() still returns the permit', afterThrow, 1);

A semaphore generalises the mutex: n permits instead of one. The state is a count and a queue, and the only real design decision is in release. Handing the permit straight to the next waiter, rather than doing free++ and letting them race for it, is what makes the seventh assertion hold — free stays at zero throughout, because the permit was never free. It also makes the queue fair: first parked, first served.

Compare this with exercise 21's mapLimit. mapLimit owns the work, so it can start exactly limit runners and never needs a queue at all. A semaphore does not own the work, so callers arrive whenever they like and it needs somewhere to park them. Use mapLimit for a known list; use a semaphore to bound something that is called from all over — a database pool, an image resizer, an outbound API with a rate limit.

The failure modes are the mutex's. Forget the release and you leak a permit; leak all of them and every future acquire hangs silently. use(fn) with a finally exists so that callers never touch acquire and release directly, and the eighth assertion is the reason it is worth the extra method.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.