Programming Search⌘K

Conceptadvanced

Work stealing

Also called work stealing, work-stealing scheduler, work-stealing deque, task stealing, ForkJoinPool, child stealing, continuation stealing.

Work stealing is a way to share tasks among worker threads. Each worker keeps its own deque of tasks, and a worker with no tasks takes the oldest task from the deque of another worker.

Applies to
core-languages

Idea

Work stealing is a way to share tasks among a fixed set of worker threads. Each worker has its own queue of tasks. A worker adds the tasks that it creates to its own queue and runs them from there. In the words of Wikipedia, when a processor "runs out of work, it looks at the queues of the other processors" and steals their work items.1

The main benefit is that busy workers do not coordinate at all. "as long as all processors have work to do, no scheduling overhead occurs".1 Coordination happens only when a worker is idle, and then the idle worker pays for it. Compare a pool with one shared queue, where every worker takes every task from the same place.

Work stealing suits work that splits itself: a task that creates smaller tasks, which create smaller tasks again. Divide-and-conquer algorithms, such as a parallel sum or a parallel sort, work like this. The example files show the rules on a small case. Two workers split the range [0, 8) into pieces and add the numbers. Worker w1 starts with nothing and steals its first task.

How it works

A deque for each worker

Each worker keeps its tasks in a double-ended queue, a deque, and uses the two ends for different things. The scheme of the Java fork/join framework, which adapts the scheme of Cilk, is typical:2

  • A worker pushes the tasks that it creates onto the bottom of its own deque.
  • A worker takes its next task from the bottom of its own deque, in LIFO order: the newest task first.
  • An idle worker picks another worker at random and takes a task from the top of that worker's deque, in FIFO order: the oldest task first.2
  • A worker that finds nothing to steal backs off and tries again later. When all workers are idle, they block until new work arrives.2

Why the two ends

The owner and the thief use opposite ends, and this has two effects:2

  • Less contention. Lea's paper says that this "reduces contention by having stealers operate on the opposite side of the deque as owners".2 Most of the time, only the owner touches its deque, and the owner's push and pop can avoid locks. The owner and a thief can only interfere "if the deque is about to become empty", and only that case needs a lock.2
  • Large steals. In a recursive split, the oldest task in a deque is the one that was split first, so it is the largest. "an older stolen task is likely to provide a larger unit of work", so one steal gives the thief a lot of work.2 In the example, w1 steals [0, 4), half of the whole range, in its first step.

The owner's LIFO order also helps the cache: the newest task usually uses the data that the worker has just touched. The .NET thread pool takes local tasks in LIFO order "to preserve cache locality and reduce contention".3

Joining

A task often waits for the subtasks that it forked. A worker that waits by blocking would waste its thread. So in the Java fork/join framework, a worker that reaches a join "processes other tasks, if available, until the target task is noticed to have completed".2 Rayon's join works the same way. The current thread runs the first closure and makes the second available to other threads. If a thief has taken the second closure, the current thread looks for other work while it waits.4

Child stealing and continuation stealing

When a task forks a child, one of the two must wait in the deque, where a thief can take it:1

  • Child stealing. The parent continues, and the child waits in the deque. This is "easier to implement as a library, without compiler support". Threading Building Blocks, the .NET Task Parallel Library and OpenMP use it.1
  • Continuation stealing. The worker runs the child at once, as a function call, and the rest of the parent waits in the deque. Cilk Plus uses it.1

The difference matters for memory. With continuation stealing, the stack space is bounded by the space of a one-processor run times the number of processors. With child stealing there is no such bound: a loop that forks n children can fill a deque with n tasks.1

In languages

LanguageVerdictNote
PythonAbsent
C++Library
JavaStandard library
CLibraryThe C standard library has no work-stealing scheduler; OpenMP tasks use child stealing. No separate example file. Alternative: A model of the rules, as in the C++ example.
C#Standard library
JavaScriptAbsent
TypeScriptAbsentTypeScript runs on a JavaScript engine, with one thread for each event loop and no work-stealing scheduler. No example file exists. Alternative: A model of the rules, as in the JavaScript example.
GoNative
RustLibrary
KotlinStandard libraryOn the JVM, Kotlin uses the Java ForkJoinPool, as in the Java example; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyThe database schedules its own work; a query does not create tasks.
BashAbsentBash has no scheduler for tasks. No example file exists.
PowerShellAbsentPowerShell has no work-stealing scheduler; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no tasks.
CSSDoes not applyStyle rules have no tasks.
Regular expressionsDoes not applyA pattern has no tasks.
Language Verdict Mechanism
Python absent no work-stealing scheduler in the standard library
JavaScript absent one thread for each event loop
TypeScript absent as JavaScript
Java stdlib ForkJoinPool, Executors.newWorkStealingPool
Kotlin stdlib the Java ForkJoinPool on the JVM
C# stdlib the .NET thread pool, with a local queue for each thread
Go native the runtime scheduler steals goroutines between Ps
Rust library Rayon, and the multi-threaded Tokio runtime
C library OpenMP tasks
C++ library Threading Building Blocks
Bash absent no scheduler for tasks
PowerShell absent no work-stealing scheduler
SQL n/a the database schedules its own work
Regex n/a a pattern has no tasks
HTML/CSS n/a markup and style rules have no tasks
  • Java. ForkJoinPool "differs from other kinds of ExecutorService mainly by virtue of employing work-stealing".5 A task calls fork to push a subtask and join to wait for it. Executors.newWorkStealingPool creates a work-stealing pool with one target thread for each processor.6 The Java example runs a model of the rules, and then a real sum on a ForkJoinPool.
  • C#. The .NET thread pool has one global FIFO queue and a local queue for each thread. A task that another task creates goes to the local queue of its thread.3 An idle thread looks in its own local queue, then in the global queue, and "then in the local queues of other threads".3
  • Go. Each P, a processor in the Go runtime, has a local run queue of goroutines. stealWork "attempts to steal a runnable goroutine or timer from any P", and runqsteal takes half of the goroutines of the other P.7
  • Rust. Rayon uses "a fixed pool of worker threads" and work stealing to run the two closures of join in parallel only when CPUs are idle.4 Tokio's multi-threaded scheduler also steals tasks.8
  • Other languages. The model in the example files works in any language. A real scheduler needs threads and a deque that is safe for an owner and thieves at the same time, so most programs use a library.
PythonGitHub
from collections import deque

# A step-by-step model of a work-stealing scheduler with two workers.
# Each worker has a deque. The left end is the top (oldest task); the right end is the bottom (newest task).
# A task is a range [lo, hi). A range of more than 2 numbers splits into two halves; a smaller range is a leaf that adds its numbers.
WORKERS = 2
deques = [deque() for _ in range(WORKERS)]
leaves = [0] * WORKERS
total = 0

deques[0].append((0, 8))
round_number = 0
while any(deques):
    round_number += 1
    for w in range(WORKERS):
        if deques[w]:
            lo, hi = deques[w].pop()  # the owner takes the newest task (LIFO)
            how, source = "pops", ""
        else:
            victim = next((v for v in range(WORKERS) if v != w and deques[v]), None)
            if victim is None:
                print(f"round {round_number}: w{w} is idle")
                continue
            lo, hi = deques[victim].popleft()  # a thief takes the oldest task (FIFO)
            how, source = "steals", f" from w{victim}"
        if hi - lo > 2:
            mid = (lo + hi) // 2
            deques[w].append((lo, mid))
            deques[w].append((mid, hi))
            print(f"round {round_number}: w{w} {how} [{lo}, {hi}){source} and splits it")
        else:
            total += sum(range(lo, hi))
            leaves[w] += 1
            print(f"round {round_number}: w{w} {how} [{lo}, {hi}){source} and runs it")

print("leaves run:", ", ".join(f"w{w} {n}" for w, n in enumerate(leaves)))
print("sum:", total)
Output
round 1: w0 pops [0, 8) and splits it
round 1: w1 steals [0, 4) from w0 and splits it
round 2: w0 pops [4, 8) and splits it
round 2: w1 pops [2, 4) and runs it
round 3: w0 pops [6, 8) and runs it
round 3: w1 pops [0, 2) and runs it
round 4: w0 pops [4, 6) and runs it
round 4: w1 is idle
leaves run: w0 2, w1 2
sum: 28
  • Verdict: absent. The Python standard library has no work-stealing scheduler. This file is a model: it shows the rules step by step, with two lists in place of two threads.
  • Each worker takes its own newest task with pop, from the right end. A thief takes the oldest task of another worker with popleft, from the left end.
  • In round 1, worker w1 has no work, so it steals [0, 4), the oldest and largest task of w0. After that, both workers split and run their own tasks, and they do not touch the same deque.
#include <algorithm>
#include <array>
#include <deque>
#include <iostream>
#include <string>
#include <utility>

// A step-by-step model of a work-stealing scheduler with two workers.
// Each worker has a deque. The front is the top (oldest task); the back is the bottom (newest task).
// A task is a range [lo, hi). A range of more than 2 numbers splits into two halves; a smaller range is a leaf that adds its numbers.
int main() {
    constexpr int workers = 2;
    std::array<std::deque<std::pair<int, int>>, workers> deques;
    std::array<int, workers> leaves{};
    int total = 0;

    deques[0].push_back({0, 8});
    auto busy = [&] {
        return std::any_of(deques.begin(), deques.end(), [](const auto& d) { return !d.empty(); });
    };
    for (int round = 1; busy(); ++round) {
        for (int w = 0; w < workers; ++w) {
            std::pair<int, int> task;
            std::string how = "pops";
            std::string source;
            if (!deques[w].empty()) {
                task = deques[w].back();  // the owner takes the newest task (LIFO)
                deques[w].pop_back();
            } else {
                int victim = -1;
                for (int v = 0; v < workers; ++v) {
                    if (v != w && !deques[v].empty()) {
                        victim = v;
                        break;
                    }
                }
                if (victim == -1) {
                    std::cout << "round " << round << ": w" << w << " is idle\n";
                    continue;
                }
                task = deques[victim].front();  // a thief takes the oldest task (FIFO)
                deques[victim].pop_front();
                how = "steals";
                source = " from w" + std::to_string(victim);
            }
            auto [lo, hi] = task;
            std::cout << "round " << round << ": w" << w << ' ' << how << " [" << lo << ", " << hi << ')'
                      << source;
            if (hi - lo > 2) {
                int mid = (lo + hi) / 2;
                deques[w].push_back({lo, mid});
                deques[w].push_back({mid, hi});
                std::cout << " and splits it\n";
            } else {
                for (int i = lo; i < hi; ++i) total += i;
                ++leaves[w];
                std::cout << " and runs it\n";
            }
        }
    }

    std::cout << "leaves run: w0 " << leaves[0] << ", w1 " << leaves[1] << '\n';
    std::cout << "sum: " << total << '\n';
}
Output
round 1: w0 pops [0, 8) and splits it
round 1: w1 steals [0, 4) from w0 and splits it
round 2: w0 pops [4, 8) and splits it
round 2: w1 pops [2, 4) and runs it
round 3: w0 pops [6, 8) and runs it
round 3: w1 pops [0, 2) and runs it
round 4: w0 pops [4, 6) and runs it
round 4: w1 is idle
leaves run: w0 2, w1 2
sum: 28
  • Verdict: library. The C++ standard library has no work-stealing pool. Intel Threading Building Blocks has a work-stealing scheduler.
  • This file is a model of the rules, with two std::deque objects in place of two threads. pop_back is the owner's LIFO pop, and pop_front is the thief's FIFO steal.
  • A real scheduler must make the two ends safe to use from two threads at the same time. That is the hard part of a work-stealing deque, and a model on one thread does not show it.
JavaGitHub
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class Main {
    // A real fork/join task: split the range until it is small, then add its numbers.
    static class SumTask extends RecursiveTask<Long> {
        final int lo, hi;

        SumTask(int lo, int hi) {
            this.lo = lo;
            this.hi = hi;
        }

        @Override
        protected Long compute() {
            if (hi - lo <= 10_000) {
                long sum = 0;
                for (int i = lo; i < hi; i++) sum += i;
                return sum;
            }
            int mid = (lo + hi) >>> 1;
            SumTask left = new SumTask(lo, mid);
            left.fork(); // push the left half on this worker's deque, where an idle worker can steal it
            long right = new SumTask(mid, hi).compute();
            return right + left.join();
        }
    }

    public static void main(String[] args) {
        model();
        try (ForkJoinPool pool = new ForkJoinPool(4)) {
            System.out.println("ForkJoinPool sum of [0, 1000000): " + pool.invoke(new SumTask(0, 1_000_000)));
        }
    }

    // A step-by-step model of a work-stealing scheduler with two workers.
    // Each worker has a deque. The first element is the top (oldest task); the last is the bottom (newest task).
    // A task is a range [lo, hi). A range of more than 2 numbers splits into two halves; a smaller range is a leaf that adds its numbers.
    static void model() {
        final int workers = 2;
        List<ArrayDeque<int[]>> deques = new ArrayList<>();
        for (int w = 0; w < workers; w++) deques.add(new ArrayDeque<>());
        int[] leaves = new int[workers];
        int total = 0;

        deques.get(0).addLast(new int[] {0, 8});
        for (int round = 1; deques.stream().anyMatch(d -> !d.isEmpty()); round++) {
            for (int w = 0; w < workers; w++) {
                int[] task;
                String how = "pops", source = "";
                if (!deques.get(w).isEmpty()) {
                    task = deques.get(w).pollLast(); // the owner takes the newest task (LIFO)
                } else {
                    int victim = -1;
                    for (int v = 0; v < workers; v++) {
                        if (v != w && !deques.get(v).isEmpty()) {
                            victim = v;
                            break;
                        }
                    }
                    if (victim == -1) {
                        System.out.printf("round %d: w%d is idle%n", round, w);
                        continue;
                    }
                    task = deques.get(victim).pollFirst(); // a thief takes the oldest task (FIFO)
                    how = "steals";
                    source = " from w" + victim;
                }
                int lo = task[0], hi = task[1];
                if (hi - lo > 2) {
                    int mid = (lo + hi) / 2;
                    deques.get(w).addLast(new int[] {lo, mid});
                    deques.get(w).addLast(new int[] {mid, hi});
                    System.out.printf("round %d: w%d %s [%d, %d)%s and splits it%n", round, w, how, lo, hi, source);
                } else {
                    for (int i = lo; i < hi; i++) total += i;
                    leaves[w]++;
                    System.out.printf("round %d: w%d %s [%d, %d)%s and runs it%n", round, w, how, lo, hi, source);
                }
            }
        }
        System.out.printf("leaves run: w0 %d, w1 %d%n", leaves[0], leaves[1]);
        System.out.println("sum: " + total);
    }
}
Output
round 1: w0 pops [0, 8) and splits it
round 1: w1 steals [0, 4) from w0 and splits it
round 2: w0 pops [4, 8) and splits it
round 2: w1 pops [2, 4) and runs it
round 3: w0 pops [6, 8) and runs it
round 3: w1 pops [0, 2) and runs it
round 4: w0 pops [4, 6) and runs it
round 4: w1 is idle
leaves run: w0 2, w1 2
sum: 28
ForkJoinPool sum of [0, 1000000): 499999500000
  • Verdict: stdlib. ForkJoinPool is a work-stealing pool. fork pushes a task on the deque of the current worker, and join waits for it, running other tasks in the meantime.
  • The first part is a model of the rules, with two ArrayDeque objects in place of two threads. pollLast is the owner's LIFO pop, and pollFirst is the thief's FIFO steal.
  • The second part uses a real ForkJoinPool with four workers. Which worker runs which half changes from run to run, but the sum does not.
  • Executors.newWorkStealingPool also gives a work-stealing pool.
using System;
using System.Collections.Generic;
using System.Linq;

// A step-by-step model of a work-stealing scheduler with two workers.
// Each worker has a deque (a LinkedList). The first node is the top (oldest task); the last node is the bottom (newest task).
// A task is a range [lo, hi). A range of more than 2 numbers splits into two halves; a smaller range is a leaf that adds its numbers.
const int Workers = 2;
var deques = Enumerable.Range(0, Workers).Select(_ => new LinkedList<(int Lo, int Hi)>()).ToArray();
var leaves = new int[Workers];
int total = 0;

deques[0].AddLast((0, 8));
for (int round = 1; deques.Any(d => d.Count > 0); round++)
{
    for (int w = 0; w < Workers; w++)
    {
        (int Lo, int Hi) task;
        string how = "pops", source = "";
        if (deques[w].Count > 0)
        {
            task = deques[w].Last!.Value; // the owner takes the newest task (LIFO)
            deques[w].RemoveLast();
        }
        else
        {
            int victim = Enumerable.Range(0, Workers).FirstOrDefault(v => v != w && deques[v].Count > 0, -1);
            if (victim == -1)
            {
                Console.WriteLine($"round {round}: w{w} is idle");
                continue;
            }
            task = deques[victim].First!.Value; // a thief takes the oldest task (FIFO)
            deques[victim].RemoveFirst();
            how = "steals";
            source = $" from w{victim}";
        }
        var (lo, hi) = task;
        if (hi - lo > 2)
        {
            int mid = (lo + hi) / 2;
            deques[w].AddLast((lo, mid));
            deques[w].AddLast((mid, hi));
            Console.WriteLine($"round {round}: w{w} {how} [{lo}, {hi}){source} and splits it");
        }
        else
        {
            for (int i = lo; i < hi; i++) total += i;
            leaves[w]++;
            Console.WriteLine($"round {round}: w{w} {how} [{lo}, {hi}){source} and runs it");
        }
    }
}

Console.WriteLine($"leaves run: {string.Join(", ", leaves.Select((n, w) => $"w{w} {n}"))}");
Console.WriteLine($"sum: {total}");
Output
round 1: w0 pops [0, 8) and splits it
round 1: w1 steals [0, 4) from w0 and splits it
round 2: w0 pops [4, 8) and splits it
round 2: w1 pops [2, 4) and runs it
round 3: w0 pops [6, 8) and runs it
round 3: w1 pops [0, 2) and runs it
round 4: w0 pops [4, 6) and runs it
round 4: w1 is idle
leaves run: w0 2, w1 2
sum: 28
  • Verdict: stdlib. The .NET thread pool has a local queue for each of its threads, and an idle thread steals from the local queues of the other threads. Tasks that a task starts go to the local queue of its thread.
  • This file is a model of the rules, with two LinkedList objects in place of two threads. RemoveLast is the owner's LIFO pop, and RemoveFirst is the thief's FIFO steal.
  • The model shows why a thief takes the oldest task: in a recursive split, the oldest task is the largest piece of work.
JavaScriptGitHub
// A step-by-step model of a work-stealing scheduler with two workers.
// Each worker has a deque (an array). Index 0 is the top (oldest task); the end is the bottom (newest task).
// A task is a range [lo, hi). A range of more than 2 numbers splits into two halves; a smaller range is a leaf that adds its numbers.
const WORKERS = 2;
const deques = Array.from({ length: WORKERS }, () => []);
const leaves = new Array(WORKERS).fill(0);
let total = 0;

deques[0].push([0, 8]);
let round = 0;
while (deques.some((d) => d.length > 0)) {
  round += 1;
  for (let w = 0; w < WORKERS; w++) {
    let task;
    let how;
    let source = "";
    if (deques[w].length > 0) {
      task = deques[w].pop(); // the owner takes the newest task (LIFO)
      how = "pops";
    } else {
      const victim = deques.findIndex((d, v) => v !== w && d.length > 0);
      if (victim === -1) {
        console.log(`round ${round}: w${w} is idle`);
        continue;
      }
      task = deques[victim].shift(); // a thief takes the oldest task (FIFO)
      how = "steals";
      source = ` from w${victim}`;
    }
    const [lo, hi] = task;
    if (hi - lo > 2) {
      const mid = Math.floor((lo + hi) / 2);
      deques[w].push([lo, mid], [mid, hi]);
      console.log(`round ${round}: w${w} ${how} [${lo}, ${hi})${source} and splits it`);
    } else {
      for (let i = lo; i < hi; i++) total += i;
      leaves[w] += 1;
      console.log(`round ${round}: w${w} ${how} [${lo}, ${hi})${source} and runs it`);
    }
  }
}

console.log(`leaves run: ${leaves.map((n, w) => `w${w} ${n}`).join(", ")}`);
console.log(`sum: ${total}`);
Output
round 1: w0 pops [0, 8) and splits it
round 1: w1 steals [0, 4) from w0 and splits it
round 2: w0 pops [4, 8) and splits it
round 2: w1 pops [2, 4) and runs it
round 3: w0 pops [6, 8) and runs it
round 3: w1 pops [0, 2) and runs it
round 4: w0 pops [4, 6) and runs it
round 4: w1 is idle
leaves run: w0 2, w1 2
sum: 28
  • Verdict: absent. JavaScript runs each event loop on one thread, and it has no work-stealing scheduler. This file is a model of the rules, with two arrays in place of two threads.
  • The owner takes its newest task with pop, from the end of its array. A thief takes the oldest task of another worker with shift, from the start.
  • In round 1, worker w1 steals the large task [0, 4) and splits it further. One steal gives w1 half of all the work.
package main

import (
	"fmt"
	"strings"
)

// A task is a range [lo, hi). A range of more than 2 numbers splits into two halves;
// a smaller range is a leaf that adds its numbers.
type task struct{ lo, hi int }

// A step-by-step model of a work-stealing scheduler with two workers.
// Each worker has a deque (a slice). Index 0 is the top (oldest task); the end is the bottom (newest task).
func main() {
	const workers = 2
	deques := make([][]task, workers)
	leaves := make([]int, workers)
	total := 0

	deques[0] = append(deques[0], task{0, 8})
	busy := func() bool {
		for _, d := range deques {
			if len(d) > 0 {
				return true
			}
		}
		return false
	}
	for round := 1; busy(); round++ {
		for w := range workers {
			var t task
			how, source := "pops", ""
			if n := len(deques[w]); n > 0 {
				t, deques[w] = deques[w][n-1], deques[w][:n-1] // the owner takes the newest task (LIFO)
			} else {
				victim := -1
				for v := range workers {
					if v != w && len(deques[v]) > 0 {
						victim = v
						break
					}
				}
				if victim == -1 {
					fmt.Printf("round %d: w%d is idle\n", round, w)
					continue
				}
				t, deques[victim] = deques[victim][0], deques[victim][1:] // a thief takes the oldest task (FIFO)
				how, source = "steals", fmt.Sprintf(" from w%d", victim)
			}
			if t.hi-t.lo > 2 {
				mid := (t.lo + t.hi) / 2
				deques[w] = append(deques[w], task{t.lo, mid}, task{mid, t.hi})
				fmt.Printf("round %d: w%d %s [%d, %d)%s and splits it\n", round, w, how, t.lo, t.hi, source)
			} else {
				for i := t.lo; i < t.hi; i++ {
					total += i
				}
				leaves[w]++
				fmt.Printf("round %d: w%d %s [%d, %d)%s and runs it\n", round, w, how, t.lo, t.hi, source)
			}
		}
	}

	parts := make([]string, workers)
	for w, n := range leaves {
		parts[w] = fmt.Sprintf("w%d %d", w, n)
	}
	fmt.Println("leaves run:", strings.Join(parts, ", "))
	fmt.Println("sum:", total)
}
Output
round 1: w0 pops [0, 8) and splits it
round 1: w1 steals [0, 4) from w0 and splits it
round 2: w0 pops [4, 8) and splits it
round 2: w1 pops [2, 4) and runs it
round 3: w0 pops [6, 8) and runs it
round 3: w1 pops [0, 2) and runs it
round 4: w0 pops [4, 6) and runs it
round 4: w1 is idle
leaves run: w0 2, w1 2
sum: 28
  • Verdict: native. The Go runtime scheduler is a work-stealing scheduler. Each P, a processor in the runtime, has a local run queue of goroutines, and an idle P steals half of the goroutines of another P.
  • Go code does not see the deques, so this file is a model of the rules, with two slices in place of two workers.
  • The owner takes the last element of its slice, and a thief takes the first element of another slice.
RustGitHub
use std::collections::VecDeque;

// A step-by-step model of a work-stealing scheduler with two workers.
// Each worker has a deque. The front is the top (oldest task); the back is the bottom (newest task).
// A task is a range [lo, hi). A range of more than 2 numbers splits into two halves; a smaller range is a leaf that adds its numbers.
fn main() {
    const WORKERS: usize = 2;
    let mut deques: Vec<VecDeque<(u32, u32)>> = vec![VecDeque::new(); WORKERS];
    let mut leaves = [0; WORKERS];
    let mut total = 0;

    deques[0].push_back((0, 8));
    let mut round = 0;
    while deques.iter().any(|d| !d.is_empty()) {
        round += 1;
        for w in 0..WORKERS {
            let ((lo, hi), how, source) = if let Some(task) = deques[w].pop_back() {
                (task, "pops", String::new()) // the owner takes the newest task (LIFO)
            } else {
                let victim = (0..WORKERS).find(|&v| v != w && !deques[v].is_empty());
                let Some(victim) = victim else {
                    println!("round {round}: w{w} is idle");
                    continue;
                };
                let task = deques[victim].pop_front().unwrap(); // a thief takes the oldest task (FIFO)
                (task, "steals", format!(" from w{victim}"))
            };
            if hi - lo > 2 {
                let mid = (lo + hi) / 2;
                deques[w].push_back((lo, mid));
                deques[w].push_back((mid, hi));
                println!("round {round}: w{w} {how} [{lo}, {hi}){source} and splits it");
            } else {
                total += (lo..hi).sum::<u32>();
                leaves[w] += 1;
                println!("round {round}: w{w} {how} [{lo}, {hi}){source} and runs it");
            }
        }
    }

    let parts: Vec<String> = leaves.iter().enumerate().map(|(w, n)| format!("w{w} {n}")).collect();
    println!("leaves run: {}", parts.join(", "));
    println!("sum: {total}");
}
Output
round 1: w0 pops [0, 8) and splits it
round 1: w1 steals [0, 4) from w0 and splits it
round 2: w0 pops [4, 8) and splits it
round 2: w1 pops [2, 4) and runs it
round 3: w0 pops [6, 8) and runs it
round 3: w1 pops [0, 2) and runs it
round 4: w0 pops [4, 6) and runs it
round 4: w1 is idle
leaves run: w0 2, w1 2
sum: 28
  • Verdict: library. The standard library has no work-stealing pool. Rayon and the multi-threaded Tokio runtime are work-stealing schedulers from crates.
  • This file is a model of the rules, with two VecDeque values in place of two threads. pop_back is the owner's LIFO pop, and pop_front is the thief's FIFO steal.
  • With Rayon, rayon::join(a, b) runs a on the current thread and lets an idle worker steal b.
  • Work sharing. The opposite approach: a scheduler gives each new task to a processor when the task is created. Work stealing moves tasks between processors less, because no task moves while all processors are busy.1
  • A shared queue. A pool where all workers take from one queue, as in Run tasks on a thread pool. It is simpler, but all workers contend for the one queue.8
  • Steal half. Go and Tokio take half of the tasks of another worker in one steal, not one task.78 This spreads a burst of new tasks over the idle workers quickly.
  • FIFO mode. ForkJoinPool has an asyncMode for "event-style tasks that are never joined". In this mode, each worker takes its own tasks in FIFO order.5
  • Executors. A work-stealing pool is one kind of executor. Code submits tasks to it as to any other executor.5
  • Green threads. The Go runtime uses work stealing to share goroutines among its worker threads.7

Pitfalls

  • Tasks that are too small. Each fork has a cost, like a procedure call.2 If the leaves of a split are tiny, this cost is larger than the work. Split until a piece is large enough, then run it as a plain loop, as the Java example does with pieces of 10,000 numbers.
  • Tasks that are too large. A task that never splits cannot be shared. If one worker gets all the work in one task, the other workers have nothing to steal.
  • Blocking. A worker that blocks on I/O or a lock does no work, and it cannot run the tasks in its deque. ForkJoinPool tries to add threads when tasks wait to join, but "no such adjustments are guaranteed in the face of blocked I/O or other unmanaged synchronization".5
  • Many idle thieves. When a batch of work ends, many workers can become idle at the same time and all try to steal. Tokio limits the workers that search for work at the same time to about half of the processors.8
  • Order. Tasks do not run in the order of submission. Code that depends on the order must enforce it in another way.

Cost

  • Time. The randomized algorithm of Blumofe and Leiserson runs a computation in expected time T1/P + O(T∞) on P processors. T1 is the time of a serial run, and T∞ is the time with unlimited processors.1 So the expected time is within a constant factor of the best possible.1
  • Space. With continuation stealing, the stack space is at most S1 × P, where S1 is the stack space of a serial run.1 Child stealing has no such bound.1
  • Operations. A push or a pop by the owner is cheap, because it does not contend with other workers in the common case.2 A steal is more expensive, because it must synchronize with the owner and other thieves. This is acceptable because "relatively few tasks are stolen in most fork/join programs".2

History

According to Wikipedia, the idea goes back to the Multilisp language and to work on parallel functional languages in the 1980s.1 Blumofe and Leiserson published an analysis of randomized work stealing in 1999, and the Cilk language uses work stealing in its scheduler.1 Doug Lea described a Java fork/join framework that adapts the tactics of the Cilk scheduler.2 ForkJoinPool in the Java standard library is a work-stealing pool of the same kind.5 .NET Framework 4 added work stealing to the thread pool.3 In 2019, Tokio described the rewrite of its scheduler as a work-stealing scheduler, the design that Go, Erlang and Java also use.8

References

  1. Wikipedia, Work stealing, introduction; Algorithm; Child stealing vs. continuation stealing; Efficiency; Space usage; Multiprogramming variant
  2. A Java Fork/Join Framework (Doug Lea), 2.1 Work-Stealing; 3.1 Deques
  3. Microsoft Learn, TaskScheduler class, The global queue vs. local queues; Work stealing
  4. Rayon documentation, function rayon::join, description
  5. Java SE 21 API, java.util.concurrent.ForkJoinPool, class description; ForkJoinPool constructor, asyncMode
  6. Java SE 21 API, java.util.concurrent.Executors, newWorkStealingPool
  7. Go source, src/runtime/proc.go, Goroutine scheduler comment; stealWork; runqsteal
  8. Tokio blog, Making the Tokio scheduler 10x faster (2019), Work-stealing scheduler; Throttle stealing

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/G7XJGG/text.yaml