KatInterview

Build a Thread-Safe Future: Chaining and Parallel Fan-In

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencyfuturesthreading

Last 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 chain must be invoked with value.
  • If the object has already been settled, this call must be a no-op and return False.
  • Returns True exactly 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 timeout is given (in seconds) and elapses before the result arrives, raise TimeoutError.
  • A timeout of 0.0 must raise TimeoutError immediately 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 chain is called, fn must run immediately (in the calling thread is fine).
  • The returned AsyncResult[R] is settled as soon as fn finishes.

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 results is 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^4 for join_all.
  • Multiple threads may concurrently call resolve, wait, or chain on the same instance.
  • Callbacks passed to chain are guaranteed not to raise exceptions.

Edge Cases to Handle

  • chain called after resolve has already been called.
  • join_all([]) — empty input.
  • wait(timeout=0.0) on an unsettled result must raise TimeoutError immediately.
  • The same AsyncResult instance appearing more than once in the join_all input list.
  • All inputs to join_all already settled before join_all is 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.