KatInterview

Run Work Items on Manual Python Threads and Debug Them in Linux

Data Structure DesignModel answer
MediumModel answerData Structure Designpythonthreadingconcurrency

Last 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.