Bounded Worker Threads and Linux Thread Diagnostics

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement a bounded multi-threaded runner run_concurrently using only Python's low-level threading primitives (threading.Thread, threading.Lock, and threading.Event). High-level concurrency frameworks—including concurrent.futures.ThreadPoolExecutor, ProcessPoolExecutor, multiprocessing, and asyncio—are prohibited.

Given a callable func and a finite items iterable, run_concurrently must evaluate func(item) on manually managed worker threads and return one Outcome record per input element in the exact order those elements appeared in items:

@dataclass
class Outcome:
    status: str                            # "ok", "error", or "skipped"
    value: Any = None                      # return value when status == "ok"
    error: Optional[BaseException] = None  # raised exception when status == "error"

def run_concurrently(
    func: Callable[[Any], Any],
    items: Iterable[Any],
    max_workers: int,
    stop: Optional[threading.Event] = None,
    stop_on_error: bool = False,
    name_prefix: str = "worker",
) -> List[Outcome]:

Your implementation must satisfy the following rules:

  1. Argument validation & lazy inputs: If max_workers < 1, raise ValueError immediately before consuming items or starting any threads. items may be any finite Iterable (including a single-pass generator).
  2. Bounded, named, non-daemon workers: Spawn at most min(max_workers, N) worker threads (where N is the item count, spawning 0 threads when N == 0). Name them f"{name_prefix}-0", f"{name_prefix}-1", ..., configure them with daemon=False, execute func exclusively on worker threads (never on the caller thread), and join() every started thread before returning—even if thread creation fails partway through or waiting is interrupted.
  3. Minimal locking & exactly-once claims: Coordinate work assignment so each input index 0 .. N - 1 is claimed at most once, releasing the coordination lock before invoking func(item) so calls execute concurrently.
  4. Per-slot exception isolation: If func(item) returns val, store Outcome("ok", value=val) at that item's index. If it raises any BaseException exc (including SystemExit), capture Outcome("error", error=exc) at that index and keep the worker alive for remaining work unless halting is triggered.
  5. Cooperative halting: When stop is set (prior to or during execution), or as soon as any call fails while stop_on_error=True, stop assigning new indices. Calls already running finish and record "ok" or "error", while all never-started positions return Outcome("skipped").

Alongside the implementation, be prepared to discuss how Python's Global Interpreter Lock (GIL) affects I/O-bound versus CPU-bound callables, how to inspect native threads on Linux (ps, top, /proc), how Linux Thread IDs relate to Python thread identifiers in logs, and why point-in-time OS thread snapshots alone cannot prove or disprove deadlocks.

Examples

Example 1

items = [4, 0, 6, 12]
outcomes = run_concurrently(lambda n: 120 // n, items, max_workers=2)
# outcomes -> [
#   Outcome(status="ok", value=30, error=None),
#   Outcome(status="error", value=None, error=ZeroDivisionError("integer division or modulo by zero")),
#   Outcome(status="ok", value=20, error=None),
#   Outcome(status="ok", value=10, error=None),
# ]

Walk-through: Two threads (worker-0 and worker-1) pull indices dynamically outside the assignment lock. Index 1 (0) raises ZeroDivisionError, which is stored in outcomes[1] without killing the worker. Because stop_on_error defaults to False, indices 2 and 3 still run, and all four results are returned in input order after both threads are joined.

Example 2

def normalize_tag(tag: str) -> str:
    if not tag:
        raise ValueError("empty tag")
    return tag.upper()

outcomes = run_concurrently(
    normalize_tag,
    ["db", "", "cache", "queue"],
    max_workers=1,
    stop_on_error=True,
    name_prefix="runner",
)
# outcomes -> [
#   Outcome(status="ok", value="DB", error=None),
#   Outcome(status="error", value=None, error=ValueError("empty tag")),
#   Outcome(status="skipped", value=None, error=None),
#   Outcome(status="skipped", value=None, error=None),
# ]

Walk-through: A single non-daemon thread named "runner-0" processes index 0 ("db" -> "DB") and then encounters ValueError("empty tag") at index 1. Because stop_on_error=True, index assignment stops immediately, leaving indices 2 and 3 unclaimed with status "skipped".

Constraints

  • items is a finite Iterable of 0 to 10,000 elements.
  • max_workers is an integer; raise ValueError whenever max_workers < 1.
  • Use only Python standard-library threading primitives (Thread, Lock, Event); no thread/process executors or asyncio.
  • Returned List[Outcome] length must equal the number of elements in items, ordered by input position, with zero worker threads still alive when run_concurrently returns.

Step-by-step walkthrough

  1. Clarify the contract and design the output shape

    A thread is an independent stream of execution inside a single running program (process) that shares the same memory space with its sibling threads. Here we are given a function func and a finite sequence of items, and we must run func(item) across a bounded number of manually managed threads without using thread pools or asyncio.

    Before writing any code, pin down the four core behavioral rules so the runner contract is unambiguous:

    • Thread safety of func: Assume func is safe to call concurrently on separate items (or protects its own internal state). Our runner only needs to synchronize its own work-assignment bookkeeping.
    • Result order: Return one outcome per input item in the original input order, even when fast later items finish ahead of slow earlier ones.
    • Error policy: By default (stop_on_error=False), if func(item) raises an exception, store that exception at that item's position and let the remaining items run. When stop_on_error=True, stop assigning new items as soon as one call fails.
    • Cooperative cancellation: Python provides no safe way to forcibly kill a running thread mid-instruction. Instead, a threading.Event flag (stop) acts as a polite "stop taking new items" signal: calls already in progress finish normally, and unclaimed items stay marked "skipped".

    We represent each position's final state with a small Outcome record:

    from typing import Any, Optional
    from dataclasses import dataclass
    
    
    @dataclass
    class Outcome:
        """What happened to one input position."""
        status: str                            # "ok", "error", or "skipped" (never started)
        value: Any = None                      # the return value when status == "ok"
        error: Optional[BaseException] = None  # the exception when status == "error"
    
  2. Understand when Python threads speed up work

    Before promising a speedup, clarify whether func waits on external I/O (network requests, disk reads, database queries) or performs pure CPU math in Python.

    In standard CPython, the Global Interpreter Lock (GIL)—a single interpreter-wide lock that allows only one thread to execute Python bytecode instructions at any instant—stays locked during pure Python loops, but is released whenever a thread sleeps, waits on OS I/O, or calls C extensions (such as NumPy) that explicitly drop it:

    Work inside each call             1 call    4 calls across 4 threads
    --------------------------------------------------------------------
    time.sleep(0.5)  (simulates I/O)  0.50 s    0.51 s  -> ~4x speedup (GIL released while waiting)
    Pure-Python loop (3M additions)   0.05 s    0.20 s  -> ~1x speedup (threads take turns on the GIL)
    

    Threads are therefore ideal when func blocks on I/O, because all max_workers calls can wait in parallel. For CPU-bound pure-Python code on a GIL build, threads add context-switching overhead without running faster than a single loop.

  3. Key idea: lock only the index counter, never the work

    Every worker needs a way to claim the next unprocessed index 0, 1, ..., total_items - 1 so that no index is processed twice and none is skipped.

    If two threads share an unlocked counter and run claimed = next_index; next_index += 1, a race condition—a bug where correctness depends on the unpredictable timing of threads interleaving—can occur: Thread A reads 0, Thread B also reads 0 before Thread A writes 1, both process item 0, and item 1 or the final count breaks.

    To prevent that, we guard the counter with a mutex (threading.Lock, a mutual-exclusion lock that lets only one thread enter a protected code region—called a critical section—at a time). Crucially, the worker must release that lock before calling func(...):

    1. BROKEN (no lock):
       worker-0: read next=0 ──► write next=1 ──► func(items[0])
       worker-1: read next=0 ──► write next=1 ──► func(items[0])   (duplicate!)
    
    2. SERIALIZED (lock held during func — defeats concurrency!):
       worker-0: [LOCK: take 0 + func(items[0]) ...........]
       worker-1:                                            [LOCK: take 1 + func(items[1]) ...........]
    
    3. CORRECT (tiny critical section in take(); func runs outside lock):
       worker-0: [LOCK:0] ──► func(items[0]) ................... ──► [LOCK:2] ──► func(items[2])
       worker-1:          [LOCK:1] ──► func(items[1]) .......... ──► [LOCK:None] (exits)
    

    Wrapping that tiny counter inside an IndexDispenser helper makes the critical section impossible to misuse:

    from typing import Optional
    import threading
    
    
    class IndexDispenser:
        """Hands out indices 0, 1, ..., total_items - 1, each at most once, across threads."""
    
        def __init__(self, total_items: int, stop_event: threading.Event) -> None:
            self._total_items = total_items
            # _next_index: next unclaimed position in item_list (monotonically increases 0 -> total_items)
            self._next_index = 0
            self._stop_event = stop_event
            # _lock: protects the read-and-increment of _next_index so two threads never claim the same slot
            self._lock = threading.Lock()
    
        def take(self) -> Optional[int]:
            """Return the next unassigned index, or None when exhausted or stopped."""
            # Keep the critical section tiny: check stop/bounds and bump one integer, never run user work here.
            with self._lock:
                if self._stop_event.is_set() or self._next_index >= self._total_items:
                    return None
                claimed_index = self._next_index
                self._next_index += 1
                return claimed_index
    

    Pulling indices dynamically on demand also balances uneven workloads automatically: if worker-0 gets stuck on one slow network call, worker-1 simply pulls and finishes several fast items in the meantime.

  4. Write the worker loop and capture every exception

    Inside run_concurrently, we pre-fill outcomes with total_items copies of Outcome("skipped"). Each worker then runs a simple loop: claim an index, call func(item_list[index]) outside any lock, and write the result directly into outcomes[index].

    Two details are essential here:

    1. Catch BaseException inside the worker. If an uncaught exception escapes a thread's target function, Python does not raise it in the main thread—it passes it to threading.excepthook (printing a traceback to stderr) and kills that worker thread. Catching BaseException (even SystemExit) records the error cleanly in outcomes[index] and keeps the worker alive to process more items.
    2. Writing outcomes[index] needs no lock. Because IndexDispenser hands out each index at most once, no two threads ever write to the same slot of the pre-sized outcomes list, and the main thread reads outcomes only after joining all workers.
        # Phase 2: Define the worker loop. Each worker pulls indices until none remain.
        def worker() -> None:
            while True:
                index = dispenser.take()
                if index is None:
                    return
                logger.debug(
                    "item %d starts on %s (tid %d)",
                    index,
                    threading.current_thread().name,
                    threading.get_native_id(),
                )
                try:
                    # Call func OUTSIDE the dispenser lock so workers execute concurrently.
                    result_value = func(item_list[index])
                except BaseException as exc:
                    # Catch BaseException (including SystemExit) so one bad call cannot kill the worker thread.
                    # No lock is needed to write outcomes[index]: each index is claimed by at most one thread.
                    outcomes[index] = Outcome("error", error=exc)
                    if stop_on_error:
                        stop_event.set()
                else:
                    outcomes[index] = Outcome("ok", value=result_value)
    
  5. Start, name, and join a bounded pool of non-daemon threads

    Now we manage the lifecycle of the worker threads from creation to completion:

    • Bound the thread count to min(max_workers, total_items). Passing 2 items with max_workers=8 only starts 2 threads, and an empty items list starts 0 threads.
    • Set daemon=False. A daemon thread is a background thread that Python abruptly terminates mid-execution when the main program exits, risking half-written files or corrupted state. Non-daemon threads, paired with thread.join() (which blocks the caller until that thread finishes), guarantee every started call completes before run_concurrently returns.
    • Clean up if startup or waiting is interrupted. If thread.start() raises RuntimeError (for example, hitting the OS thread limit) or KeyboardInterrupt hits thread.join(), our except BaseException: block sets stop_event, joins every thread that already started, and re-raises.

    Trace run_concurrently(lambda n: 120 // n, [4, 0, 6, 12], max_workers=2) from Example 1 assuming each call takes 0.1 s:

    Time   worker-0                  worker-1                  outcomes slots [0, 1, 2, 3]
    ------------------------------------------------------------------------------------------
    0.0s   take()->0, run 120 // 4   take()->1, run 120 // 0   [skip, skip, skip, skip]
    0.1s   write slot 0 = ok(30)     write slot 1 = err(ZDE)   [ok(30), err, skip, skip]
           take()->2, run 120 // 6   take()->3, run 120 // 12
    0.2s   write slot 2 = ok(20)     write slot 3 = ok(10)     [ok(30), err, ok(20), ok(10)]
           take()->None (returns)    take()->None (returns)    main finishes join() in ~0.2s
    
  6. Inspect threads on Linux and connect OS IDs to Python logs

    On Linux, the kernel schedules every thread as its own task with a unique Thread ID (TID), also shown as LWP (lightweight process). All threads inside one process share the same Process ID (PID) (the thread-group ID, equal to the main thread's TID):

    # 1. List threads and live per-thread CPU usage
    pgrep -f my_worker_app.py                       # find the process's PID
    ps -T -p PID                                    # one row per thread; SPID column is the kernel TID
    ps -L -o pid,lwp,nlwp,stat,pcpu,comm -p PID     # LWP = TID, NLWP = thread count, STAT = thread state
    top -H -p PID                                   # live view per thread (PID column here shows TIDs!)
    pidstat -t -p PID 1                             # per-thread CPU% sampled every 1 second
    
    # 2. Read kernel thread metadata directly from procfs (needs no special permissions)
    ls /proc/PID/task                               # one subdirectory per active TID
    cat /proc/PID/task/TID/comm                     # kernel thread name (truncated to 15 characters)
    grep -E 'State|ctxt_switches' /proc/PID/task/TID/status  # state + voluntary/nonvoluntary switches
    cat /proc/PID/task/TID/wchan                    # kernel wait channel when sleeping
    
    # 3. Dump call stacks across all threads (requires ptrace permission on the target process)
    py-spy dump --pid PID                           # Python-level stack frames for every thread
    gdb -p PID -batch -ex 'thread apply all bt'     # C / native stack frames for every thread
    

    Note on permissions: py-spy and gdb attach via ptrace. On Linux systems with kernel.yama.ptrace_scope = 1 (the default on Ubuntu and many cloud hosts), attaching to a non-child process requires sudo or the CAP_SYS_PTRACE container capability, whereas /proc/PID/task/... and ps -T work as the same OS user without ptrace.

    To correlate a Linux TID from top -H or ps -T with your Python logs, use the right identifier:

    • threading.get_native_id() (Python 3.8+) returns the exact Linux kernel TID shown in ps -T, top -H, and /proc/PID/task/<TID>.
    • threading.get_ident() returns the POSIX pthread handle (a large memory address), which does not match Linux TIDs—beware that Python's standard logging format %(thread)d prints get_ident(), not get_native_id().
    • Thread.name (worker-0) is a Python string. CPython 3.13 and earlier never copied it to the kernel (so comm showed python3 for every thread), and CPython 3.14+ copies it via pthread_setname_np where Linux truncates it to 15 bytes. Logging (Thread.name, threading.get_native_id()) together—just as our worker() does—works reliably on every Python version.
  7. Distinguish thread observations from proof of correctness

    Operating-system thread metrics are point-in-time observations that suggest hypotheses; they never prove correctness or diagnose a deadlock by themselves:

    • Thread state S (interruptible sleep) is ambiguous. A thread deadlocked on Lock.acquire(), waiting on a slow HTTP socket, sitting inside time.sleep(), or waiting for the CPython GIL all appear as state S waiting on a futex or poll syscall.
    • CPU percentages are ambiguous too. 0% CPU can mean either a deadlock or normal waiting on network I/O. 100% CPU can mean useful computation or an infinite retry/spin loop. Under the GIL, 4 pure-Python threads at 25% CPU each only mean they are taking turns on a single core's worth of bytecode execution.
    • Compare multiple snapshots over time. Take 3–4 py-spy dump --pid PID stack traces several seconds apart and watch voluntary_ctxt_switches in /proc/PID/task/TID/status. If two threads keep the exact same stack frames blocked inside Lock.acquire() while context switches stay frozen, you have strong evidence of a deadlock; if stacks advance or context switches climb, the callable is slow rather than deadlocked.
    • Proof comes from invariants and tests, not top: acquiring locks in a strict order, never calling func while holding _lock, adding timeouts to external I/O calls, and writing deterministic concurrency tests (such as a threading.Barrier(3) test that fails immediately if calls are accidentally serialized).
  8. Complete solution

    from typing import Any, Callable, Iterable, List, Optional
    from dataclasses import dataclass
    import logging
    import threading
    
    logger = logging.getLogger(__name__)
    
    
    @dataclass
    class Outcome:
        """What happened to one input position."""
        status: str                            # "ok", "error", or "skipped" (never started)
        value: Any = None                      # the return value when status == "ok"
        error: Optional[BaseException] = None  # the exception when status == "error"
    
    
    class IndexDispenser:
        """Hands out indices 0, 1, ..., total_items - 1, each at most once, across threads."""
    
        def __init__(self, total_items: int, stop_event: threading.Event) -> None:
            self._total_items = total_items
            # _next_index: next unclaimed position in item_list (monotonically increases 0 -> total_items)
            self._next_index = 0
            self._stop_event = stop_event
            # _lock: protects the read-and-increment of _next_index so two threads never claim the same slot
            self._lock = threading.Lock()
    
        def take(self) -> Optional[int]:
            """Return the next unassigned index, or None when exhausted or stopped."""
            # Keep the critical section tiny: check stop/bounds and bump one integer, never run user work here.
            with self._lock:
                if self._stop_event.is_set() or self._next_index >= self._total_items:
                    return None
                claimed_index = self._next_index
                self._next_index += 1
                return claimed_index
    
    
    def run_concurrently(func: Callable[[Any], Any], items: Iterable[Any], max_workers: int,
                         stop: Optional[threading.Event] = None, stop_on_error: bool = False,
                         name_prefix: str = "worker") -> List[Outcome]:
        """Call func(item) once per item on at most max_workers manually created threads.
    
        Returns one Outcome per input position, in input order, after every started thread
        has been joined. Setting `stop` (or a failure when stop_on_error is True) stops the
        assignment of new items; calls already running finish, and the rest are "skipped".
        """
        # Phase 1: Validate max_workers before materializing items (in case items is a lazy generator).
        if max_workers < 1:
            raise ValueError("max_workers must be at least 1")
    
        # Materialize the iterable into a random-access list: e.g. ["url0", "url1", "url2"]
        item_list = list(items)
        total_items = len(item_list)
    
        stop_event = stop if stop is not None else threading.Event()
    
        # Pre-fill one "skipped" slot per input position: [Outcome("skipped"), Outcome("skipped"), ...]
        # Any index never claimed before stop_event is set naturally keeps its "skipped" status.
        outcomes: List[Outcome] = []
        for _ in range(total_items):
            outcomes.append(Outcome("skipped"))
    
        dispenser = IndexDispenser(total_items, stop_event)
    
        # Phase 2: Define the worker loop. Each worker pulls indices until none remain.
        def worker() -> None:
            while True:
                index = dispenser.take()
                if index is None:
                    return
                logger.debug(
                    "item %d starts on %s (tid %d)",
                    index,
                    threading.current_thread().name,
                    threading.get_native_id(),
                )
                try:
                    # Call func OUTSIDE the dispenser lock so workers execute concurrently.
                    result_value = func(item_list[index])
                except BaseException as exc:
                    # Catch BaseException (including SystemExit) so one bad call cannot kill the worker thread.
                    # No lock is needed to write outcomes[index]: each index is claimed by at most one thread.
                    outcomes[index] = Outcome("error", error=exc)
                    if stop_on_error:
                        stop_event.set()
                else:
                    outcomes[index] = Outcome("ok", value=result_value)
    
        # Phase 3: Start at most min(max_workers, total_items) non-daemon threads and join them all.
        worker_count = min(max_workers, total_items)
        threads: List[threading.Thread] = []
        try:
            for worker_num in range(worker_count):
                thread_name = f"{name_prefix}-{worker_num}"
                # daemon=False ensures Python will not abruptly kill in-flight work at interpreter exit.
                thread = threading.Thread(target=worker, name=thread_name, daemon=False)
                thread.start()
                threads.append(thread)
            for thread in threads:
                thread.join()
        except BaseException:
            # If OS thread creation fails or main receives KeyboardInterrupt, stop handing out new indices
            # and wait for already-started threads to finish before letting the exception propagate.
            stop_event.set()
            for thread in threads:
                thread.join()
            raise
    
        return outcomes
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a busy bakery counter with a roll of numbered paper tickets (0, 1, 2, ...) and a shelf of numbered pickup cubbies. We hire max_workers bakers (threads). Each baker walks up to the ticket roll, spends a fraction of a millisecond tearing off the next ticket number under a small mutex (threading.Lock, a lock that lets only one thread touch the counter at a time), immediately steps away from the ticket roll so other bakers can grab their own tickets, bakes that item independently, and places either the finished pastry or an error note into cubby #index before coming back for another ticket.

Why do simpler approaches fail? Spawning one brand-new thread per item (say, 20,000 threads for 20,000 items) wastes megabytes of OS stack memory per thread and crashes against operating-system thread limits. Conversely, holding the lock while calling func(item) turns a multi-threaded program into a slow single-file line, and appending results to a shared results.append(...) list scrambles the output order whenever fast later items finish before slow earlier ones.

Walk through Example 1 with items = [4, 0, 6, 12], func(n) = 120 // n, and max_workers = 2: 1. We pre-fill outcomes with 4 "skipped" placeholders: [skipped, skipped, skipped, skipped], and start two non-daemon threads (worker-0 and worker-1). 2. worker-0 locks the dispenser for an instant, claims index 0 (4), and releases the lock; worker-1 immediately claims index 1 (0). worker-0 writes outcomes[0] = Outcome("ok", 30), while 120 // 0 on worker-1 raises ZeroDivisionError, which worker-1 catches and stores at outcomes[1] = Outcome("error", error=ZeroDivisionError(...)) without dying. 3. Next, worker-0 claims index 2 (6) and writes outcomes[2] = Outcome("ok", 20), while worker-1 claims index 3 (12) and writes outcomes[3] = Outcome("ok", 10). 4. Both workers call dispenser.take(), receive None because _next_index reached 4, and exit cleanly; the main thread finishes join() on both workers and returns [ok(30), error(ZeroDivisionError), ok(20), ok(10)] in exact input order.

Complexity

Let N be the number of input items, W = min(max_workers, N) be the number of worker threads started, and C be the average duration of one func(item) call:

  • Time: Coordination takes O(N + W) total work—each item is copied once into item_list, pre-filled once in outcomes, claimed once in O(1) time inside dispenser.take(), and each of the W workers makes one final O(1) take() call that returns None. For I/O-bound calls of duration C that release the Global Interpreter Lock (GIL) (CPython's bytecode lock), wall-clock runtime is roughly ceil(N / W) * C because W calls wait in parallel; for CPU-bound pure-Python calls under the GIL, wall-clock time remains roughly N * C because only one thread runs Python bytecode at a time.
  • Space: O(N + W) memory—O(N) in Python heap memory to hold the materialized item_list and the N-element outcomes list, plus O(W) operating-system thread descriptors and reserved stack space (typically several megabytes of virtual address space per active worker thread on Linux, which is why bounding W is essential).

Edge cases

  • Empty items iterable: Materializes to [], starts 0 threads (min(max_workers, 0) == 0), and returns [] immediately.
  • Single-pass generator input: Converting items to item_list = list(items) once up front lets run_concurrently accept generators and iterators that have no len().
  • max_workers larger than len(items): Only len(items) threads are created, avoiding idle threads that wake up only to see None and exit.
  • max_workers < 1: Raises ValueError immediately before consuming items or starting any thread.
  • Callable raises SystemExit or KeyboardInterrupt subclass: Catching BaseException (rather than Exception) prevents a worker from dying silently and leaving remaining items unprocessed.
  • stop event already set before calling run_concurrently: Workers immediately get None on their first dispenser.take(), func is never called, and every slot returns Outcome("skipped").
  • OS refuses to start a thread (RuntimeError): The except BaseException: block sets stop_event, joins every thread that did start so no orphan workers keep running in the background, and re-raises the error.

Common mistakes

  • Holding the lock while calling func(item): Wrapping func(item_list[index]) inside with self._lock: forces every worker to wait in single file, destroying all concurrency.
  • Checking and incrementing _next_index without a lock: Writing if idx < n: mine = idx; idx += 1 without a mutex creates a race condition where two threads can read the same idx and run the same item twice (especially visible under heavy load or on free-threaded Python builds).
  • Spawning one thread per item instead of min(max_workers, N): Passing 50,000 items creates 50,000 OS threads and hits RuntimeError: can't start new thread or exhausts memory.
  • Letting exceptions escape the worker target: Uncaught exceptions inside threading.Thread do not propagate out of thread.join(); they print to stderr via threading.excepthook and kill that worker thread.
  • Using daemon=True without join(): Returning before workers finish causes data races on outcomes and lets interpreter shutdown kill in-flight calls mid-operation.
  • Matching Linux ps -T or top -H against threading.get_ident(): get_ident() returns the POSIX pthread handle, not the Linux kernel Thread ID; always log threading.get_native_id() to match OS tools.

Alternative approaches

  • Thread-safe queue.Queue of (index, item) pairs: Pre-populate a queue.Queue and have each worker call queue.get_nowait() until queue.Empty. This works cleanly because Queue wraps its internal deque with a Lock, though writing IndexDispenser directly makes the tiny critical section explicit and avoids building a second tuple queue in memory.
  • Static strided slicing (worker k gets k, k + W, k + 2W, ...): Eliminates locking altogether because each thread owns fixed indices, but suffers from head-of-line stragglers when one worker happens to draw several slow items while other workers finish early and sit idle.

Follow-up questions

  • How should the design adapt when the supplied function modifies shared state that lacks built-in thread safety? Our runner's lock only protects _next_index, and CPython's GIL does not make compound updates like shared_dict[k] += 1 atomic because a thread switch can happen between reading the old value and writing the incremented value. The cleanest fix is to give each call or worker its own local accumulator and merge them on the main thread after join() finishes. If mutations must happen live on one shared object, wrap just the mutation lines in a dedicated threading.Lock owned by that resource (never reuse the dispenser's lock), or funnel updates through a queue.Queue to a single writer thread.
  • Why does passing a timeout to Thread.join() leave the worker thread running rather than terminating it? Calling thread.join(timeout=2.0) only limits how long the calling thread blocks waiting; when the 2 seconds expire, join simply returns None while the worker thread keeps running in the background (check thread.is_alive() to verify). Operating systems and Python intentionally omit a forced thread.kill() API because killing a thread mid-execution would leave any locks it holds permanently locked (deadlocking every other thread) and leave shared data structures half-written. To bound runtimes safely, pass explicit timeouts to the I/O operations inside func (such as socket or HTTP request timeouts), check a cooperative threading.Event between steps, or isolate untrusted blocking code in a separate OS process that can be terminated cleanly.
  • If a cancellation flag is triggered halfway through processing a batch, how can callers tell which items finished, failed, or never ran? Pre-filling outcomes with Outcome("skipped") handles this automatically: as soon as stop.set() is called, dispenser.take() stops handing out new indices, any W calls currently running finish and overwrite their slots with "ok" or "error", and every untouched index remains "skipped". For example, if cancellation arrives after 37 of 100 items have been claimed, the caller receives a complete 100-element Outcome list containing 37 "ok"/"error" entries and 63 "skipped" entries at their exact positions, making it trivial to retry [items[i] for i, o in enumerate(outcomes) if o.status == "skipped"] later. If func itself checks stop.is_set() midway through a multi-step task, it can raise a custom CancelledError so the caller can distinguish aborted in-flight calls from genuine errors and never-started items.

Follow-up questions

Similar questions

More Coreweave interview questions

All 14 Coreweave questions →