Build a Semaphore, Latch and Barrier
🚦 What are synchronizers? They are small objects whose only job is to make threads wait for each other. A semaphore lets at most N threads into a section at once. A latch makes threads wait until some number of events have happened, like "all five services have started". A barrier makes a group of threads wait until all of them reach the same point, then lets them all continue, round after round.
Every language ships these, so why build them? Because they are the clearest test of whether you understand condition variables. Each one is fifteen lines of code built on the same pattern, and each one has a famous bug that the pattern prevents. An interviewer who asks you to "implement a semaphore using a mutex" is checking that you know that pattern cold. Once you do, a blocking queue, a read-write lock or a thread pool is the same idea with different state.
Requirements
"Implement a counting semaphore, a countdown latch and a cyclic barrier. You may only use a mutex and condition variables."
The three classes are independent, so the clarifying questions are about each one's exact behavior.
Clarifying Questions
You: Can release raise the number of permits above what the semaphore started with?
Interviewer: Yes. release always adds one permit. That is how Java's Semaphore behaves too, and it lets a semaphore that starts at 0 be used as a signal.
You: Do waiters on the semaphore need to be served in arrival order?
Interviewer: Not for now. Any waiter can take a freed permit. We may talk about fairness later.
You: Do we need timeouts, like tryAcquire(100 ms)?
Interviewer: Just a non-blocking tryAcquire that returns false immediately. Timeouts are a follow-up.
You: Can the latch be reset once it reaches zero?
Interviewer: No. It is one-shot: once open, it stays open. Counting down at zero does nothing.
You: Is the barrier used once, or many times?
Interviewer: Many times. The same barrier is used for round after round, like the steps of a simulation. Each await returns the caller's arrival order in its round: 0 for the first, parties - 1 for the last.
You: What if a thread waiting at the barrier is interrupted or times out?
Interviewer: Ignore that for now. Assume every party always arrives.
The barrier answer is the one that makes the problem interesting. A barrier that is used once is easy. A barrier that is used again and again needs to tell this round from the next one, and that is where most first attempts break.
💡 Interview tip: For any blocking primitive, ask three questions: what state does it keep, what condition does a waiter wait for, and which call makes that condition true? The answers are the fields, the
whileloop and thenotifyof your design.
Final Requirements
- Semaphore(permits):
acquire()takes a permit, waiting while none is free.tryAcquire()takes one if free and returnstrue, otherwise returnsfalsewithout waiting.release()adds a permit and wakes a waiter.availablePermits()returns the count. - At no time do more threads hold permits than were available.
- CountDownLatch(count):
countDown()lowers the count by one, never below zero.await()waits until the count is zero; once it is, every waiter, current and future, gets through.getCount()returns the count. - CyclicBarrier(parties):
await()waits untilpartiesthreads have called it in the current round, then releases all of them and starts a new round. It returns the caller's arrival index in its round. - No thread leaves a barrier round before every party has arrived in that round.
- Only a lock and condition variables may be used. A waiting thread must sleep, not spin.
- Every method is safe to call from many threads at once.
Out of scope
- Fair (first-come, first-served) semaphores, timeouts, and broken barriers (all three in Extensibility).
- Interrupting a waiting thread.
- Sharing these between processes. They live in one process's memory.