AlgoViz

Thread pool

medium 70 min

A 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

0:00 / 5:06

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

clientmain threadpoolTaskPoolqueueemptydonenoneworker 1threadrunsasleepworker 2threadrunsasleepworker 3threadrunsasleep

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 sOut per sWaiting
0 s1502000
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

    critical

    Only one job runs at a time, and nobody can submit.

    Wrong
    with self._changed:    job = self._jobs.popleft()    job.run()
    Right
    with self._changed:    job = self._jobs.popleft()job.run()
  • A flag beside the queue

    critical

    The pool can close between the check and the put. The job is never run and its future never ends.

    Wrong
    if self.closed: raise Rejectedself.queue.put(job)
    Right
    with self._changed:    if self._closed: raise Rejected    self._jobs.append(job)    self._changed.notify()
  • An error ends the worker

    critical

    After N bugs the pool accepts work and does none.

    Wrong
    while True:    job = take()    job.fn()
    Right
    while True:    job = take()    job.run()     # stores the error in the future
  • A queue without a limit

    major

    Overload turns into memory and waiting instead of an answer.

    Wrong
    queue = Queue()
    Right
    queue = Queue(maxsize=100)# and a policy for full
  • Waiting for your own pool

    critical

    Enough parents take all workers, and no child can start.

    Wrong
    def parent():    return pool.submit(child).result()
    Right
    def 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.