Thread pool
medium 70 minA few threads that live long, one queue with a limit, and a loop: take, run, repeat.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Tasks, a queue and workers that stay. Watch who runs what.
Operations
Six tasks, three workers
The whole life of a pool: start, submit, wait, reuse, finish, close.
Step 1 of 10
Ready
Asleep costs almost nothing
Three workers are started once. Each sleeps on the queue.
Step 1: Ready
def submit(self, fn, *args): job = Job(fn, args) with self._changed: if self._closed: raise Rejected self._jobs.append(job) self._changed.notify() return job.resultdef _work(self): while True: with self._changed: while not self._jobs and not self._closed: self._changed.wait() if not self._jobs: return job = self._jobs.popleft() job.run()def shutdown(self): with self._changed: self._closed = True self._changed.notify_all() for t in self._threads: t.join()- Watch
- The queue and the workers
- Result
- Six tasks on three threads
Worker 1 goes from A to D without sleeping. That is the reuse.
In the real world
The same thread pool doing real jobs. Pick one and step through it.
40 workers. A task needs 0.2 s, then 2 s, then 0.2 s again.
Step 1 of 5
Normal
| In per s | Out per s | Waiting | |
|---|---|---|---|
| 0 s | 150 | 200 | 0 |
| 11 s | |||
| 70 s | |||
| 71 s | |||
| 227 s |
40 / 0.2 = 200 can be done, 150 come.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Running inside the lock
criticalOnly one job runs at a time, and nobody can submit.
Wrongwith self._changed: job = self._jobs.popleft() job.run()Rightwith self._changed: job = self._jobs.popleft()job.run()A flag beside the queue
criticalThe pool can close between the check and the put. The job is never run and its future never ends.
Wrongif self.closed: raise Rejectedself.queue.put(job)Rightwith self._changed: if self._closed: raise Rejected self._jobs.append(job) self._changed.notify()An error ends the worker
criticalAfter N bugs the pool accepts work and does none.
Wrongwhile True: job = take() job.fn()Rightwhile True: job = take() job.run() # stores the error in the futureA queue without a limit
majorOverload turns into memory and waiting instead of an answer.
Wrongqueue = Queue()Rightqueue = Queue(maxsize=100)# and a policy for fullWaiting for your own pool
criticalEnough parents take all workers, and no child can start.
Wrongdef parent(): return pool.submit(child).result()Rightdef parent(done): pool.submit(child).add_done_callback(done)
Interview tips
Write it in this order
- Job with its future.
- The loop.
- Submit, then shutdown.
- Same lock for both.
Two numbers
- Workers from W and C.
- Cut to what is scarce.
- Queue from patience.
At the edge
- Full: who pays?
- Failed: who hears it?
- Closing: what is lost?
Never
- Wait for your own pool.
- Leave thread-locals.
- Ignore futures.