Thread pool
medium 70 minA few threads that live long, one queue with a limit, and a loop: take, run, repeat.
Watch lesson5:06
Work stealing
A queue per worker, and thieves with good manners
The point: with very many small tasks the shared queue is the bottleneck. Give each worker its own, and let the idle ones steal from the other end.
Why
One lock for all
Suppose taking a task from the shared queue holds its lock for 1 microsecond. Then all workers together cannot take more than 1,000,000 tasks per second, whatever the number of cores. If a task needs 10 microseconds of computing, the ceiling is reached with 10 workers. For tasks of 10 milliseconds it would be 10,000 workers, and the question does not matter.
Each worker has its own deque
1/3Many small queues
A worker touches its own deque nearly all the time. Nobody else does, so there is little waiting.
owns (dies together)uses
Steal from the other end
Three operations. A lock keeps it simple. Real pools use a lock-free deque in which the owner is almost free of cost.
import threadingfrom collections import dequeclass WorkDeque: def __init__(self): self._lock = threading.Lock() self._jobs = deque() def push(self, job): with self._lock: self._jobs.append(job) def pop(self): # the owner: newest first with self._lock: return self._jobs.pop() if self._jobs else None def steal(self): # a thief: oldest first with self._lock: return self._jobs.popleft() if self._jobs else NoneLines 9 to 11
New work goes to the owner's end.
Shared queue or stealing?
| One shared queue | Work stealing | |
|---|---|---|
| Order | First in, first out | None |
| Task size | Any, not tiny | Tiny is fine |
| Tasks that create tasks | Need care, see waiting for itself | Made for it |
| Fairness | By arrival | A worker may stay with its own pile |
| Code | 40 lines | Use a library |
| Blocking tasks | A worker less | A worker less, and its pile waits for thieves |