Run Work Items on Manual Python Threads and Debug Them in Linux
Data Structure DesignModel answerLast updated
Fan a function out over a list using a fixed number of hand-made Python threads, capture every result or error, join cleanly, then inspect the live threads from the Linux shell.
You are given a function fn and a finite list of independent inputs. Describe, and write code for, how you would call fn once per input concurrently, and then explain how you would look at the resulting threads on a Linux machine.
Restrictions: use only the basic threading module (Thread, Lock, and similar). Do not use ThreadPoolExecutor, ProcessPoolExecutor, multiprocessing pools, or asyncio.
Part 1 - Coordinate the threads
Write a function that takes fn, a list of inputs, and a maximum worker count, and then:
- starts at most that many manually created threads;
- guarantees each input position is processed exactly once, with none skipped and none handled twice;
- stores, for each input position, either the return value or the exception raised;
- waits for every started thread before returning.
Explain what shared state needs protection, how you keep the critical section short, and what happens when fn raises.
Part 2 - Inspect threads on Linux
Give commands that list the threads of a running process and show what each one is doing. Explain how an OS thread ID relates to what your application logs, and say what a snapshot can and cannot tell you when you suspect a deadlock, a wait, or a slow call.
Things you may want to clarify first: is fn thread-safe, does it block on I/O or burn CPU, should a failure stop remaining work, must results follow input order, and can calls be cancelled?
Hints
Hint 1
Hand out work with a shared counter guarded by a lock. Each worker takes the next index inside the lock, releases it, and only then calls the function.
Hint 2
Preallocate a results list and an errors list the same length as the input. Each worker writes only to its own slot, so those writes need no lock.
Hint 3
On Linux, a thread has its own TID separate from the process PID. Look at /proc/<pid>/task, ps with thread flags, or top in thread mode, and name your threads so logs can be matched to them.
Hint 4
A single snapshot shows state at one instant. A thread asleep in the kernel could be waiting on I/O, a lock, or a timer, so combine several samples with stack dumps and logs.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify first
Ask whether fn is thread-safe, whether it is I/O-bound or CPU-bound, whether a failure should stop remaining work, whether output must be in input order, and whether a call can block forever. In CPython, the GIL means threads help with I/O-bound or GIL-releasing work, but generally not with pure-Python CPU-bound loops. Say this up front rather than promising a speedup.
Part 1: Coordinating the threads
Design
- Use
min(max_workers, len(items))worker threads, each created withthreading.Thread. - Shared state: a
next_indexcounter. It is the only thing that needs a lock. - Preallocated
resultsanderrorslists with one slot per input. Each index is claimed by exactly one worker, so writes to different slots never collide and need no lock. - Each worker loops: acquire lock, read and increment the counter, release lock, exit if the index is past the end, otherwise call
fnoutside the lock. - Calling
fnwhile holding the lock would serialize everything and defeat the purpose. It also risks deadlock iffnever touches the same lock.
Code
import threading
def run_concurrently(fn, items, max_workers=4):
n = len(items)
results = [None] * n
errors = [None] * n
lock = threading.Lock()
next_index = 0
def worker():
nonlocal next_index
while True:
with lock:
i = next_index
next_index += 1
if i >= n:
return
try:
results[i] = fn(items[i])
except BaseException as exc:
errors[i] = exc
threads = [
threading.Thread(target=worker, name=f"worker-{k}")
for k in range(min(max_workers, n))
]
for t in threads:
t.start()
for t in threads:
t.join()
return results, errors
Why it is correct
- Exactly-once: the increment happens under the lock, so every worker gets a unique index. Indices at or beyond
nmean no work is left. - Order: results are written by position, so output order matches input order regardless of completion order.
- Exceptions: an uncaught exception in a thread would only print a traceback and kill that worker, silently leaving items undone. Catching inside the loop records the error for that slot and keeps the worker alive. After joining, the caller can inspect
errorsand re-raise, aggregate, or report. - Joining: threads are non-daemon, and we join all of them, so nothing is abandoned mid-run. If
start()fails partway, join only the threads that were started.
Complexity: O(n) calls to fn, O(n) extra memory, O(1) lock operations per item.
Variations and trade-offs
- To stop on first failure, add a
threading.Event; workers check it before claiming an index. Items not run keepNonein both lists, which should be documented. - Use a
queue.Queueof indices as an alternative to the counter. It is simple, but the counter has less overhead and no sentinel handling. - Cancellation is cooperative only. Python cannot safely kill a thread, so a call stuck in
fncan only be abandoned with a timeout onjoin, and that leaves the thread running.
Common mistakes
- Calling
fninside the lock. - Reading and incrementing the counter in separate critical sections.
- Appending results in completion order and losing the mapping to inputs.
- Not catching exceptions, or forgetting to join.
- Using
t.run()instead oft.start(), which executes in the caller's thread.
Part 2: Inspecting threads on Linux
Process ID vs thread ID. A process has a PID. Each thread has its own TID, and the main thread's TID equals the PID.
Commands
ls /proc/<pid>/tasklists TIDs.ps -T -p <pid>lists threads (SPID column);ps -L -o pid,tid,stat,pcpu,wchan:20,comm -p <pid>adds state and the kernel wait channel.top -H -p <pid>shows live per-thread CPU usage.cat /proc/<pid>/task/<tid>/statusand.../statgive state and context-switch counts.py-spy dump --pid <pid>orgdb -p <pid>withthread apply all btgives stacks, if those tools are installed and permitted.
Linking to application logs. Python 3.8+ exposes threading.get_native_id(), which returns the OS TID. Log it together with threading.current_thread().name, for example in the log format. Then a hot TID in top -H can be matched to worker-2 and to the item being processed. Naming threads at creation makes this practical.
What observation can and cannot prove
- State
S(sleeping) could mean blocked on I/O, on a lock, or on a timer.wchanand stacks narrow it down but do not settle it. - High CPU on one thread under the GIL may mean the others are simply waiting for the interpreter, not deadlocked.
- A snapshot is one instant. Take several samples over time. If the same threads show the same stacks and zero progress, a deadlock or hang is likely.
- None of this proves the code is correct. Races and lost updates may never appear in a given run. Correctness comes from reasoning about the lock discipline, tests with many iterations and varied timing, and a clear ownership rule for shared data.
Summary
Protect only the index counter, call fn outside the lock, write per-index slots, catch and record exceptions, and join every thread. On Linux, use TIDs, thread names, and repeated samples with stacks to explain behavior, while remembering that observation is evidence, not proof.