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

Problem

Why a thread per task breaks, in numbers

The point: we do not build a pool to be fast. We build it to have a limit and one place that knows it.

The task

Pictures to shrink

A shop lets people upload pictures. Each must be shrunk to three sizes. Shrinking takes about 200 ms of computing. Uploads come in bursts: after a newsletter, 500 in one second. The server has 8 cores.

500 pictures at once

A thread eachA pool of 8
Threads5008
Computing in all500 x 0.2 s = 100 sthe same 100 s
Shortest possible time100 s / 8 cores = 12.5 s63 rounds x 0.2 s = 12.6 s
First picture doneLate: 500 threads share 8 cores, so most finish near the endAfter 0.2 s
Average time until doneclose to 12.5 sabout half of it, 6.4 s
Open pictures in memory5008, the rest are only file names
The total is the same. The order is what changes: eight at a time finish one after another, instead of all together at the end. Assumption: no overhead for switching.

Requirements

What the pool must promise

PromiseQuestion that led to it
At most N tasks run at onceWhat is scarce here?
At most L tasks waitWhat happens in a burst?
A clear answer when full or closedWhat does the caller see?
The result or the error reaches the callerDoes anybody read it?
A failing task harms nobody elseWhat if a picture is broken?
A clean end: nothing accepted is lostWhat happens when we deploy?
Out of scope unless asked: priorities, delays, retries. Those belong to a job scheduler that uses a pool.

Questions to ask first. Compute or wait (number of workers)? Does the caller need the result (submit or execute)? May we refuse (policy)? Must the order hold, per user or over all? What may be lost at the end (how we close)?