Thread pool
medium 70 minA few threads that live long, one queue with a limit, and a loop: take, run, repeat.
Watch lesson5:06
Verify
Trace it, test it, and six things to check
The point: tests for a pool use gates, not sleeps. Then they are fast and they fail for one reason.
By hand
Six tasks, three workers
| Event | Queue | W1 | W2 | W3 | Done |
|---|---|---|---|---|---|
| Created | empty | idle | idle | idle | |
| submit A | empty | A | idle | idle | |
| submit B, C, D | D | A | B | C | |
| submit E, F | D, E, F | A | B | C | |
| A ends | E, F | D | B | C | A |
| B and C end | empty | D | E | F | A, B, C |
| All end | empty | idle | idle | idle | A to F |
| shutdown | closed | gone | gone | gone | A to F |
By machine
Tests that hold the door
Python
import threadingfrom collections import dequefrom concurrent.futures import Futureclass Rejected(Exception): """The pool did not take the job. Nothing was started."""class Job: def __init__(self, fn, args): self.fn, self.args, self.result = fn, args, Future() def run(self): if not self.result.set_running_or_notify_cancel(): return # cancelled while it waited try: value = self.fn(*self.args) except BaseException as e: self.result.set_exception(e) # the caller sees it, the worker lives on else: self.result.set_result(value)class TaskPool: def __init__(self, workers, limit): if workers < 1 or limit < 1: raise ValueError("at least one worker and one place in the queue") self._changed = threading.Condition() # guards _jobs and _closed self._jobs = deque() self._limit = limit self._closed = False self._threads = [threading.Thread(target=self._work, name=f"worker-{i}") for i in range(workers)] for t in self._threads: t.start() def _work(self): while True: with self._changed: while not self._jobs and not self._closed: self._changed.wait() if not self._jobs: return # closed, and nothing is left job = self._jobs.popleft() job.run() # the lock is open again def submit(self, fn, *args): job = Job(fn, args) with self._changed: if self._closed: raise Rejected("the pool is closed") if len(self._jobs) >= self._limit: raise Rejected("the queue is full") self._jobs.append(job) self._changed.notify() return job.result def shutdown(self, wait=True): with self._changed: self._closed = True self._changed.notify_all() if wait: for t in self._threads: t.join() def shutdown_now(self): with self._changed: self._closed = True left = list(self._jobs) self._jobs.clear() self._changed.notify_all() for job in left: job.result.cancel() return len(left)gate, started = threading.Event(), threading.Event()def hold(): started.set() gate.wait() return "held"pool = TaskPool(workers=1, limit=2)first = pool.submit(hold)started.wait() # now the only worker is busysecond, third = pool.submit(len, "ab"), pool.submit(lambda: 1 / 0)try: pool.submit(len, "no") print("accepted too much")except Rejected as e: print("refused:", e)gate.set()print(first.result(2), second.result(2))try: third.result(2)except ZeroDivisionError: print("the error reached the caller")print("worker lives:", pool.submit(len, "abc").result(2))pool.shutdown()try: pool.submit(len, "late")except Rejected as e: print("refused:", e)print("threads left:", sum(t.is_alive() for t in pool._threads))What each line proves
| Line | Promise | Bug it finds |
|---|---|---|
| Third submit into two places | The limit | A queue without one |
third.result | Errors reach the caller | A swallowed exception |
len after the failure | Workers survive | A loop that ends on an error |
| Submit after shutdown | Closed is closed | Flag and queue under different locks |
| Threads left | Nobody hangs | A missing notify_all |
Extend
What changes if...
| Extension | Change | Where to read |
|---|---|---|
| Priorities | A heap instead of the deque, plus aging | job scheduler |
| Run later | A heap by time, workers wait until the first is due | job scheduler |
| Order per user | Hash the user to one worker, each with its own queue | coordination |
| Survive a crash | The queue must be outside the process | A message queue |