Build a Fire-Once Event Gate for Concurrent Threads
Data Structure DesignModel answerLast 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 returnsTrueif the gate was open before the call or opened during the wait, andFalseif the time ran out first.- A
wait()issued after the gate is already open returnsTrueimmediately. 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The gate has one piece of state, a boolean _fired, which only ever moves from False to True. Three pieces make it correct:
- A mutex protecting every access to the flag.
- A condition variable created on that same mutex. Waiters sleep on it, and
fire()wakes them all. - A predicate loop in
wait()that re-checks the flag after every wakeup.
The central rule
The waiter's check of the flag and its decision to sleep must happen under the same lock that fire() holds while setting the flag and broadcasting. Condition.wait() releases the lock and suspends the thread atomically, so there is no gap in which a notification can slip by.
Why there are no lost wakeups
Consider a waiter W and a firer F. One of them takes the lock first.
- W first: W sees
False, callscond.wait(), which atomically releases the lock and enqueues W. F can only enter afterwards, so itsnotify_all()reaches W. - F first: F sets
_fired = Truebefore releasing the lock. W then seesTrueand returns immediately without sleeping.
Either order is safe.
Timeouts
Use a deadline, not a duration. Compute deadline = time.monotonic() + timeout once. On each loop iteration, compute remaining = deadline - now. If remaining <= 0, stop and return the current value of the flag. Otherwise wait for at most remaining. This way a spurious wakeup or an unrelated notification cannot restart the full timeout or end the wait early with the wrong answer.
time.monotonic() is used because wall-clock changes (NTP adjustments, DST) would otherwise stretch or shrink the wait.
The return value is decided by the flag as observed under the lock. If fire() races with the timer, the final check sees True and the call returns True. A timeout is reported only if the flag was seen False with no time left.
Implementation
import threading
import time
from typing import Optional
class OneShotTrigger:
def __init__(self):
self._lock = threading.Lock()
self._cond = threading.Condition(self._lock)
self._fired = False
def fire(self) -> None:
with self._cond:
if self._fired:
return # idempotent
self._fired = True
self._cond.notify_all() # wake every waiter
def wait(self, timeout: Optional[float] = None) -> bool:
if timeout is not None and timeout < 0:
raise ValueError("timeout must be non-negative")
with self._cond:
if timeout is None:
while not self._fired:
self._cond.wait()
return True
deadline = time.monotonic() + timeout
while not self._fired:
remaining = deadline - time.monotonic()
if remaining <= 0:
return False
self._cond.wait(remaining)
return True
def is_fired(self) -> bool:
with self._lock:
return self._fired
Condition.wait_for(lambda: self._fired, timeout) does the same deadline loop internally and is an acceptable shorter answer, provided you can explain what it does.
Complexity
fire(): O(1) under the lock plus O(W) to wake W waiters, which any broadcast must pay.wait(): O(1) work per wakeup; the thread sleeps in the OS between wakeups, so there is no CPU spinning.is_fired(): O(1).- Space: O(1) plus the condition's internal waiter queue, O(W).
Edge cases
timeout=None: blocks until fired, so it always returnsTrue.timeout=0.0: the loop checks the flag first; if it isFalse,remaining <= 0and the call returnsFalseat once. No blocking occurs.- Wait after fire: the predicate is already true, so it returns
Trueimmediately. - Concurrent
fire()calls: serialized by the lock; the first sets the flag and notifies, the rest return early. - Many waiters:
notify_allis essential.notify()wakes one thread and strands the rest. - Negative timeout: invalid input; raising
ValueErroris a clear choice (state it either way).
Common mistakes
- Calling
cond.wait(timeout)once and returning its result. It can return early without the flag being set, and its return value does not mean what you need. - Using
if not self._firedinstead ofwhile, which breaks under spurious wakeups. - Using
notify()instead ofnotify_all(). - Checking the flag outside the lock and then sleeping, which reopens the lost-wakeup window.
- Passing the full timeout again after each wakeup, so the total wait can far exceed the requested time.
- Using
time.time()instead of a monotonic clock. - Sleep-polling the flag, which violates the no-busy-waiting requirement and adds latency.
Note on is_fired()
Under CPython's GIL a bare read would work, but taking the lock is cheap, makes the memory-visibility guarantee explicit, and remains correct on free-threaded builds. It is also what you would write in Java or C++.
Likely follow-ups
Adding reset(). Naively clearing the flag creates a race: fire() broadcasts, reset() runs before the woken waiters reacquire the lock, and they see False and go back to sleep, missing a real fire. A generation counter fixes it. fire() increments the generation and sets the flag. Each waiter records the generation on entry and loops while not fired and generation == entry_generation, so any fire after it began waiting releases it even if a reset follows. You should also define the semantics of a reset racing with a fire.
Without condition variables. Use an atomic integer (0 = closed, 1 = open). wait does an acquire-load and returns if it is 1; otherwise it calls a futex wait with the expected value 0 and the remaining time, re-checking after each return since futex returns can be spurious. fire does a compare-and-swap from 0 to 1 and, only if it succeeded, issues a futex wake for all waiters. Release/acquire ordering ensures that writes made before fire() are visible to threads that return from wait().