Thread pool
medium 70 minA few threads that live long, one queue with a limit, and a loop: take, run, repeat.
Watch lesson5:06
Sizing
Workers, queue length, and the time a task waits
The point: two numbers, workers and queue length, and both come from a question about time.
Workers
Three examples, worked out
| Work | Wait W | Compute C | On 8 cores | And then? |
|---|---|---|---|---|
| Shrink a picture | 0 ms | 200 ms | 8 + 1 = 9 | Done |
| Call a payment service | 190 ms | 10 ms | 8 x (1 + 19) = 160 | The service allows 40 at once, so 40 |
| Read and compute | 30 ms | 30 ms | 8 x (1 + 1) = 16 | Measure 12, 16, 20 |
Queue
A length is a time
If 40 workers finish 200 tasks per second together, a queue of 1,000 is five seconds of waiting. Choose the longest time a caller may wait, and multiply.
Queue length
Python
import mathdef plan(cores, wait_ms, compute_ms, scarce=None, patience_s=0.5): workers = math.ceil(cores * (1 + wait_ms / compute_ms)) if wait_ms == 0: workers = cores + 1 if scarce is not None: workers = min(workers, scarce) per_second = workers / ((wait_ms + compute_ms) / 1000) if wait_ms == 0: per_second = min(per_second, cores / (compute_ms / 1000)) return workers, round(per_second), int(patience_s * per_second)print("pictures", plan(8, 0, 200))print("payments", plan(8, 190, 10, scarce=40))Full
What near 100 percent feels like
One worker, random arrivals and random task times (the M/M/1 model)
| Busy | Average time in the system, in task times |
|---|---|
| 50 percent | 1 / (1 - 0.5) = 2 |
| 80 percent | 1 / (1 - 0.8) = 5 |
| 90 percent | 1 / (1 - 0.9) = 10 |
| 95 percent | 1 / (1 - 0.95) = 20 |
Response times are high and all workers are busy. What do you do?
BreaksDouble the workers
- How
- Change the number and look.
- Limit
- If the database is the bottleneck, it gets more to do at once and becomes slower.
- Choose when
- Never without a look at where they wait.
WorksLonger queue
- How
- Accept more.
- Limit
- The same speed, longer waits, later errors.
- Choose when
- For short bursts only.
StrongSee where workers stand
- How
- Take a dump. All in one call: that resource is the limit, protect it. All computing: the cores are. Then refuse early.
- Limit
- Needs a minute of looking.
- Choose when
- Always first.