Debug and Extend a Priority-Aware Python Thread Pool
Company: Bytedance
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: easy
Interview Round: Onsite
# Debug and Extend a Priority-Aware Python Thread Pool
You inherit a Python thread-pool implementation that accepts callables and runs them on a fixed number of worker threads. Extend it so `submit(fn, priority)` schedules lower numeric priorities before higher numeric priorities, while tasks with the same priority run in submission order. Explain how you would debug the existing implementation and make shutdown, exceptions, and concurrent submissions safe.
### Constraints & Assumptions
- A task already running is not preempted when a higher-priority task arrives.
- Multiple producer threads may call `submit` concurrently.
- A task exception must not kill a worker or leave bookkeeping permanently inconsistent.
- `shutdown(wait=True)` rejects new work and waits for accepted tasks to finish.
### Clarifying Questions to Ask
- Does shutdown drain queued work or cancel work that has not started?
- Should callers receive a future for results and exceptions?
- Is starvation of low-priority work acceptable?
- Are task priorities mutable after submission?
### Solving Hints
Identify the invariants shared by producers, workers, and shutdown. Use a deterministic secondary key when two tasks have equal priority, and reason about every transition while holding or releasing synchronization primitives.
### What a Strong Answer Covers
- A reproducible debugging plan that checks races, worker liveness, queue accounting, and shutdown ordering.
- A thread-safe priority queue with stable FIFO ordering for equal priorities.
- Clear ownership of locks, conditions, worker lifecycle, task completion, and exception propagation.
- Protection against deadlock, missed wakeups, premature shutdown, and leaked worker threads.
- Tests that coordinate threads deterministically instead of depending on timing sleeps.
### Follow-up Questions
- How would you add cancellation for work that has not started?
- How could you mitigate starvation without violating the priority contract too aggressively?
- When would processes or async I/O be a better choice than Python threads?
Quick Answer: Debug and extend a Python thread pool with stable priority scheduling under concurrent submissions. Define safe behavior for worker failures, exceptions, shutdown, cancellation, starvation, and deterministic race testing.