KatInterview

Build a Fire-Once Event Gate for Concurrent Threads

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencycondition-variablethreading

Last updated

Design a thread-safe one-shot event gate with fire, timed wait and non-blocking status check, avoiding lost wakeups, spurious-wakeup bugs and busy-waiting.

Fire-Once Event Gate

Worker threads frequently have to pause until some shared event happens: an initialization step finishes, a config is loaded, or a shutdown request arrives. A simple building block for this is a one-shot gate. It starts closed, opens exactly once, and stays open forever after.

Implement a thread-safe class OneShotTrigger with this interface:

class OneShotTrigger:
    def __init__(self):
        ...

    def fire(self) -> None:
        """Open the gate and release every thread currently waiting."""

    def wait(self, timeout: float = None) -> bool:
        """Block until the gate is open or the timeout elapses.

        Returns True if the gate is open, False if the wait timed out.
        """

    def is_fired(self) -> bool:
        """Non-blocking check: True if fire() has ever been called."""

Required behavior

  • fire() opens the gate and wakes all blocked waiters. Calling it again later must be safe and change nothing.
  • wait() with no timeout blocks until the gate opens. With a timeout (seconds, >= 0), it blocks at most that long. It returns True if the gate was open before the call or opened during the wait, and False if the time ran out first.
  • A wait() issued after the gate is already open returns True immediately.
  • wait(timeout=0.0) never blocks and simply reports the current state.
  • is_fired() never blocks.

Constraints

  • Any number of threads may call any of the three methods concurrently.
  • No busy-waiting (no spin loops or sleep-polling).
  • Spurious wakeups must not cause a wrong result.
  • A thread that begins waiting at the same moment fire() is broadcasting must not be left asleep.

Examples

trigger = OneShotTrigger()
results = []

def worker():
    results.append(trigger.wait())

t = threading.Thread(target=worker)
t.start()
time.sleep(0.05)
trigger.fire()
t.join()

assert results == [True]
assert trigger.is_fired() is True
trigger = OneShotTrigger()
assert trigger.wait(timeout=0.1) is False
assert trigger.is_fired() is False

What to deliver

Write the implementation and explain why it is correct. Cover the lost-wakeup race, how you handle timeouts, and which edge cases you considered.

Hints

Hint 1

Pair a boolean flag with a mutex and a condition variable built on that same mutex. Every read or write of the flag should happen while holding it.

Hint 2

A single call to a timed condition wait is not enough, since it can return early for reasons unrelated to the flag. Re-check the flag in a loop, and compute an absolute deadline once using a monotonic clock so each iteration waits only for the remaining time.

Hint 3

Use a broadcast (notify-all) in fire(), not notify-one, or most waiters will sleep forever. Also decide how to treat a timeout of 0 and a negative timeout.