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

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

one per workerStealingPool- decks: List<WorkDeque>- left: int+ fork(me, job)+ run(me)- find(me): JobWorkDeque- jobs: deque<Job>+ push(job)+ pop(): newest+ steal(): oldest

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 None

Lines 9 to 11

New work goes to the owner's end.

1 of 3

Shared queue or stealing?

One shared queueWork stealing
OrderFirst in, first outNone
Task sizeAny, not tinyTiny is fine
Tasks that create tasksNeed care, see waiting for itselfMade for it
FairnessBy arrivalA worker may stay with its own pile
Code40 linesUse a library
Blocking tasksA worker lessA worker less, and its pile waits for thieves
A fair mix: tasks from outside go to a shared queue, tasks from inside to the own deque. Tokio works like that, with one global queue and a local queue per worker.