AlgoViz

Thread pool

medium 70 min

A 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

EventQueueW1W2W3Done
Createdemptyidleidleidle
submit AemptyAidleidle
submit B, C, DDABC
submit E, FD, E, FABC
A endsE, FDBCA
B and C endemptyDEFA, B, C
All endemptyidleidleidleA to F
shutdownclosedgonegonegoneA to F
Six tasks, three threads, none started twice. In the fifth row worker 1 goes from A to D without sleeping.

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))
The gate keeps the worker busy for as long as the test wants. No test sleeps and hopes.
Edit and run it in your browser

What each line proves

LinePromiseBug it finds
Third submit into two placesThe limitA queue without one
third.resultErrors reach the callerA swallowed exception
len after the failureWorkers surviveA loop that ends on an error
Submit after shutdownClosed is closedFlag and queue under different locks
Threads leftNobody hangsA missing notify_all

Extend

What changes if...

ExtensionChangeWhere to read
PrioritiesA heap instead of the deque, plus agingjob scheduler
Run laterA heap by time, workers wait until the first is duejob scheduler
Order per userHash the user to one worker, each with its own queuecoordination
Survive a crashThe queue must be outside the processA message queue