Thread pool
medium 70 minA 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 each | A pool of 8 | |
|---|---|---|
| Threads | 500 | 8 |
| Computing in all | 500 x 0.2 s = 100 s | the same 100 s |
| Shortest possible time | 100 s / 8 cores = 12.5 s | 63 rounds x 0.2 s = 12.6 s |
| First picture done | Late: 500 threads share 8 cores, so most finish near the end | After 0.2 s |
| Average time until done | close to 12.5 s | about half of it, 6.4 s |
| Open pictures in memory | 500 | 8, the rest are only file names |
Requirements
What the pool must promise
| Promise | Question that led to it |
|---|---|
| At most N tasks run at once | What is scarce here? |
| At most L tasks wait | What happens in a burst? |
| A clear answer when full or closed | What does the caller see? |
| The result or the error reaches the caller | Does anybody read it? |
| A failing task harms nobody else | What if a picture is broken? |
| A clean end: nothing accepted is lost | What happens when we deploy? |
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)?