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

Implementation

Job, constructor, worker loop, submit, shutdown

The point: write the worker loop first. The rest follows from it.

A thread pool from nothing

The unit of work, as an object. It catches everything the code throws, because the worker must survive.

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)

Lines 5 to 6

One error type for both refusals. The promise that nothing was started lets the caller try again without fear.

1 of 5

Why it is built this way

  • Java has this class: FutureTask. C++ has std::packaged_task. Say so, and use them.
  • Async code in JavaScript resolves or rejects a promise: the same two roads.