Build a Thread-Safe Future: Chaining and Parallel Fan-In
Data Structure DesignModel answerLast updated
Implement a generic async future primitive supporting blocking get, callback chaining, and a barrier that resolves when all parallel futures complete.
Async Task Coordination from Scratch
Asynchronous runtimes — whether in Python, Java, or JavaScript — share a common building block: a future (sometimes called a promise). It represents a value that does not exist yet, lets other code register interest in that value, and delivers the value once it arrives — without busy-waiting.
Your task is to build that building block yourself.
What to Implement
Implement a generic class AsyncResult[T] with the following four operations.
resolve(value: T) -> bool
Transitions the object from pending to settled and stores value.
- Every callback previously registered with
chainmust be invoked withvalue. - If the object has already been settled, this call must be a no-op and return
False. - Returns
Trueexactly once — on the first successful settlement.
wait(timeout: float | None = None) -> T
Blocks the calling thread until the result is available, then returns it.
- If
timeoutis given (in seconds) and elapses before the result arrives, raiseTimeoutError. - A
timeoutof0.0must raiseTimeoutErrorimmediately if the result is not yet available.
chain(fn: Callable[[T], R]) -> AsyncResult[R]
Registers a transformation to run when this result settles, and returns a new AsyncResult[R] that will hold fn(value).
- If the result is already settled at the time
chainis called,fnmust run immediately (in the calling thread is fine). - The returned
AsyncResult[R]is settled as soon asfnfinishes.
join_all(results: list[AsyncResult[T]]) -> AsyncResult[list[T]] (static)
Returns a new AsyncResult that settles only after every item in results has settled.
- The final value is a list of individual results in the same order as the input list.
- If
resultsis empty, return an already-settled result containing an empty list.
Interface
from typing import Generic, TypeVar, Callable, Optional, List
import threading
T = TypeVar('T')
R = TypeVar('R')
class AsyncResult(Generic[T]):
def __init__(self): ...
def resolve(self, value: T) -> bool: ...
def wait(self, timeout: Optional[float] = None) -> T: ...
def chain(self, fn: Callable[[T], R]) -> 'AsyncResult[R]': ...
@staticmethod
def join_all(results: List['AsyncResult[T]']) -> 'AsyncResult[List[T]]': ...
Examples
Basic resolution and chaining
r = AsyncResult()
doubled = r.chain(lambda x: x * 2)
assert r.resolve(10) is True
assert r.resolve(99) is False # already settled
assert doubled.wait() == 20
Parallel fan-in via join_all
import threading
r1, r2 = AsyncResult(), AsyncResult()
combined = AsyncResult.join_all([r1, r2])
threading.Thread(target=r1.resolve, args=("hello",)).start()
threading.Thread(target=r2.resolve, args=("world",)).start()
assert combined.wait() == ["hello", "world"]
Constraints
0 <= len(results) <= 10^4forjoin_all.- Multiple threads may concurrently call
resolve,wait, orchainon the same instance. - Callbacks passed to
chainare guaranteed not to raise exceptions.
Edge Cases to Handle
chaincalled afterresolvehas already been called.join_all([])— empty input.wait(timeout=0.0)on an unsettled result must raiseTimeoutErrorimmediately.- The same
AsyncResultinstance appearing more than once in thejoin_allinput list. - All inputs to
join_allalready settled beforejoin_allis called.
Hints
Hint 1
A single `threading.Condition` can do two jobs at once: its lock protects shared state (the settled flag, stored value, and callback list), and its wait/notify mechanism lets `wait()` sleep efficiently without polling. Think about what data needs to live under that lock and what can happen outside it.
Hint 2
The trickiest invariant is: every registered callback fires exactly once. Sketch the two races — `chain` called before `resolve`, and `chain` called after `resolve` — and make sure your lock protocol handles both without leaking or duplicating a callback.
Hint 3
For `join_all`, think of a counting latch: pre-allocate a result list of length n indexed by input position, keep a shared counter of unsettled inputs, and have each callback decrement it. The one callback that brings the counter to zero is the one responsible for settling the aggregate. Use a factory function (not a loop-body lambda) to capture each index correctly.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
AsyncResult is a two-state machine: pending → settled. The transition happens at most once and three pieces of data must always be mutually consistent: the settled flag, the stored value, and the list of pending callbacks. A single threading.Condition guards all three — its embedded lock provides mutual exclusion, and wait_for / notify_all give threads an efficient place to sleep inside wait().
The central design rule is: decide under the lock, execute callbacks outside it. Running callbacks while holding the lock is the classic bug — it creates deadlocks the moment any callback calls back into the same future, and it serializes unrelated work unnecessarily.
resolve
Acquire the lock, check _settled. If already true, return False. Otherwise set _settled = True, store the value, snapshot and clear _callbacks, call notify_all(), release the lock, then iterate the snapshot and invoke each callback. This guarantees at-most-once settlement and at-most-once callback invocation.
wait
Use Condition.wait_for(lambda: self._settled, timeout=timeout). wait_for re-checks the predicate on every wakeup (including spurious ones) and handles the timeout correctly — a bare wait() does neither. If wait_for returns False the timeout expired; raise TimeoutError.
chain / _register_callback
Acquire the lock and check _settled. If pending, append the callback and return — resolve will call it later. If already settled, read the value, release the lock, and call the callback immediately in the calling thread. The two paths are mutually exclusive under the lock, so no callback is ever lost or called twice.
join_all
Pre-allocate values = [None] * n and remaining = [n] (a list so a closure can mutate it). For each input results[i], register a callback that writes v into values[i], decrements remaining[0] under a small auxiliary lock, and — if it hits zero — settles the aggregate. Use a factory function make_cb(i) to bind i per iteration; a loop-body lambda would capture the variable, not the value, and every callback would write to the last index.
Empty input is a special case: return an already-settled result containing []. Without it, remaining starts at zero and nothing ever decrements it, so the aggregate would never settle.
Complexity
| Operation | Time | Space |
|---|---|---|
resolve | O(k) for k callbacks | O(1) extra |
wait | O(1) besides blocking | O(1) |
chain | O(1) | O(1) per child |
join_all | O(n) setup; O(1) per completion | O(n) |
Common Mistakes
- Callbacks inside the lock. Leads to deadlock or poor throughput.
- Bare
wait()instead ofwait_for. Misses spurious wakeups and gets timeout semantics wrong. Noneas a sentinel for "no value." A separate_settledflag is required so thatresolve(None)works correctly.- Loop-body lambda in
join_all. All callbacks end up writing to indexn-1. - Missing empty-list guard in
join_all. The aggregate hangs forever.
Solution
from typing import Generic, TypeVar, Callable, Optional, List
import threading
T = TypeVar('T')
R = TypeVar('R')
class AsyncResult(Generic[T]):
def __init__(self):
self._cond = threading.Condition(threading.Lock())
self._settled = False
self._value: Optional[T] = None
self._callbacks: List[Callable[[T], None]] = []
def resolve(self, value: T) -> bool:
with self._cond:
if self._settled:
return False
self._value = value
self._settled = True
# Snapshot and clear so new registrations after this point
# are handled by _register_callback's fast path, not here.
callbacks = self._callbacks
self._callbacks = []
self._cond.notify_all()
# Run callbacks outside the lock to prevent deadlocks.
for cb in callbacks:
cb(value)
return True
def wait(self, timeout: Optional[float] = None) -> T:
with self._cond:
# wait_for handles spurious wakeups and timeout correctly.
if not self._cond.wait_for(lambda: self._settled, timeout=timeout):
raise TimeoutError("AsyncResult.wait timed out")
return self._value
def _register_callback(self, cb: Callable[[T], None]) -> None:
"""Registers cb to run when this result settles, or runs it
immediately if it has already settled. Always runs outside the lock."""
with self._cond:
if not self._settled:
self._callbacks.append(cb)
return
value = self._value
# Already settled: call immediately, still outside the lock.
cb(value)
def chain(self, fn: Callable[[T], R]) -> 'AsyncResult[R]':
child: AsyncResult[R] = AsyncResult()
self._register_callback(lambda v: child.resolve(fn(v)))
return child
@staticmethod
def join_all(results: List['AsyncResult[T]']) -> 'AsyncResult[List[T]]':
aggregate: AsyncResult[List[T]] = AsyncResult()
n = len(results)
if n == 0:
aggregate.resolve([])
return aggregate
values: List[Optional[T]] = [None] * n
remaining = [n] # mutable container so closures can write it
lock = threading.Lock() # guards values and remaining
def make_cb(i: int) -> Callable[[T], None]:
"""Factory binds i by value, avoiding the loop-variable capture bug."""
def cb(v: T) -> None:
with lock:
values[i] = v
remaining[0] -= 1
done = remaining[0] == 0
if done:
aggregate.resolve(values)
return cb
for i, r in enumerate(results):
r._register_callback(make_cb(i))
return aggregate
Key correctness arguments
- At-most-once settlement. The
if self._settledcheck and theself._settled = Trueassignment are in the same critical section. Only one thread can win. - No lost wakeups.
wait_forevaluates the predicate while holding the lock.resolvesets_settledand callsnotify_allunder the same lock. A waiter either sees the flag before sleeping or is woken up after. - No lost or duplicate callbacks. Under the lock, a callback is in exactly one place: the list (if pending) or already handled (if settled). The
_register_callbackfast path andresolve's snapshot are mutually exclusive. - Correct order in
join_all. Results are written by index, not appended in arrival order, so output order always matches input order regardless of which thread finishes first.