Patterncore
Master-worker
Also called master-worker, master-slave, manager-worker, boss-worker, controller-worker, scatter and gather of work.
In master-worker, a master splits a job into parts, gives the parts to identical workers that run at the same time, and combines their results into the final result.
- Family
- concurrency
- Intent
- Split a job into independent parts, give the parts to identical workers that run concurrently, and let one master combine the partial results, so that the client sees one job and one result.
- Also called
- Master-Slave
Intent
A master component distributes work to identical worker components and computes a final result from the results when the workers return.1 The pattern is Master-Slave in Pattern-Oriented Software Architecture, Volume 1.2 This page uses the name master-worker. The old terminology is a subject of controversy because of its association with slavery, and it has been replaced with other terms in some cases.3
Problem
A job is too slow for one thread, but it splits into parts that do not depend on each other, for example a count over a large range or a test over many files. The client wants to ask for the job and get one result. It does not want to know how many threads did the work, or how the job was split.
Solution
The master takes the job from the client and splits it into parts. It gives each part to a worker, and the workers run at the same time. Each worker computes a partial result for its part and gives it back. The master waits for all the workers, then combines the partial results into the final result.
┌─► worker 1: part 1 ─┐
client ─► master ────┼─► worker 2: part 2 ─┼──► master combines ─► client
splits ├─► worker 3: part 3 ─┤ the results
└─► worker 4: part 4 ─┘
The workers are identical and interchangeable. In the example from the AG Communication Systems booklet, the census bureau is the master, which takes the census by dividing the work into smaller tasks, and the census takers are the workers, which report their work to the bureau and are interchangeable.1 Clients deal directly with the master, not with the workers.1
Example
The master counts the primes below 20000. It splits the range into four equal parts, gives each part to a worker thread, waits for all of them and adds up the four counts. Each worker writes only its own result slot, so the workers share no data that changes. The last line checks the master against one loop.
parts: [(0, 5000), (5000, 10000), (10000, 15000), (15000, 20000)]
primes in each part: [669, 560, 525, 508]
primes below 20000 from the master: 2262
same as one loop: True
The examples for each language show the same program.
import threading
LIMIT = 20000
WORKERS = 4
def count_primes(lo, hi):
"""The work of one worker: count the primes in [lo, hi)."""
count = 0
for n in range(max(lo, 2), hi):
d = 2
while d * d <= n and n % d:
d += 1
if d * d > n:
count += 1
return count
def master(limit, workers):
# 1. Split the work into one part for each worker.
bounds = [limit * i // workers for i in range(workers + 1)]
parts = list(zip(bounds, bounds[1:]))
results = [0] * workers # each worker writes only its own slot
def worker(i):
results[i] = count_primes(*parts[i])
# 2. Start the workers, then wait for all of them.
threads = [threading.Thread(target=worker, args=(i,)) for i in range(workers)]
for t in threads:
t.start()
for t in threads:
t.join()
# 3. Combine the partial results.
return parts, results, sum(results)
parts, results, total = master(LIMIT, WORKERS)
print("parts:", parts)
print("primes in each part:", results)
print("primes below", LIMIT, "from the master:", total)
print("same as one loop:", total == count_primes(0, LIMIT))
parts: [(0, 5000), (5000, 10000), (10000, 15000), (15000, 20000)]
primes in each part: [669, 560, 525, 508]
primes below 20000 from the master: 2262
same as one loop: True
- Verdict: stdlib.
threading.Threadfor each worker, a result slot for each part, andjoinbefore the master combines. Because of the GIL, the threads show the structure, not a speed-up.
#include <algorithm>
#include <future>
#include <iostream>
#include <utility>
#include <vector>
constexpr int kLimit = 20000;
constexpr int kWorkers = 4;
// The work of one worker: count the primes in [lo, hi).
int count_primes(int lo, int hi) {
int count = 0;
for (int n = std::max(lo, 2); n < hi; n++) {
int d = 2;
while (d * d <= n && n % d != 0) d++;
if (d * d > n) count++;
}
return count;
}
int main() {
// 1. Split the work into one part for each worker.
std::vector<std::pair<int, int>> parts;
for (int i = 0; i < kWorkers; i++) parts.push_back({kLimit * i / kWorkers, kLimit * (i + 1) / kWorkers});
// 2. Start a thread for each part.
std::vector<std::future<int>> futures;
for (auto [lo, hi] : parts) futures.push_back(std::async(std::launch::async, count_primes, lo, hi));
// 3. Wait for each result and combine the partial results.
std::vector<int> results;
int total = 0;
for (auto& f : futures) {
results.push_back(f.get());
total += results.back();
}
std::cout << "parts: [";
for (std::size_t i = 0; i < parts.size(); i++)
std::cout << (i ? ", " : "") << "(" << parts[i].first << ", " << parts[i].second << ")";
std::cout << "]\nprimes in each part: [";
for (std::size_t i = 0; i < results.size(); i++) std::cout << (i ? ", " : "") << results[i];
std::cout << "]\nprimes below " << kLimit << " from the master: " << total << "\n";
std::cout << "same as one loop: " << (total == count_primes(0, kLimit) ? "True" : "False") << "\n";
}
parts: [(0, 5000), (5000, 10000), (10000, 15000), (15000, 20000)]
primes in each part: [669, 560, 525, 508]
primes below 20000 from the master: 2262
same as one loop: True
- Verdict: stdlib.
std::asyncwithstd::launch::asyncstarts a thread for each part, and the master callsgeton eachstd::future.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
static final int LIMIT = 20000;
static final int WORKERS = 4;
// The work of one worker: count the primes in [lo, hi).
static int countPrimes(int lo, int hi) {
int count = 0;
for (int n = Math.max(lo, 2); n < hi; n++) {
int d = 2;
while (d * d <= n && n % d != 0) d++;
if (d * d > n) count++;
}
return count;
}
public static void main(String[] args) throws Exception {
// 1. Split the work into one part for each worker.
List<int[]> parts = new ArrayList<>();
for (int i = 0; i < WORKERS; i++) parts.add(new int[] {LIMIT * i / WORKERS, LIMIT * (i + 1) / WORKERS});
List<Callable<Integer>> tasks = new ArrayList<>();
for (int[] p : parts) tasks.add(() -> countPrimes(p[0], p[1]));
// 2. Run the parts on the workers; invokeAll returns when all are done.
List<Integer> results = new ArrayList<>();
ExecutorService workers = Executors.newFixedThreadPool(WORKERS);
try {
for (Future<Integer> f : workers.invokeAll(tasks)) results.add(f.get());
} finally {
workers.shutdown();
}
// 3. Combine the partial results.
int total = results.stream().mapToInt(Integer::intValue).sum();
List<String> shown = new ArrayList<>();
for (int[] p : parts) shown.add("(" + p[0] + ", " + p[1] + ")");
System.out.println("parts: [" + String.join(", ", shown) + "]");
System.out.println("primes in each part: " + results);
System.out.println("primes below " + LIMIT + " from the master: " + total);
System.out.println("same as one loop: " + (total == countPrimes(0, LIMIT) ? "True" : "False"));
}
}
parts: [(0, 5000), (5000, 10000), (10000, 15000), (15000, 20000)]
primes in each part: [669, 560, 525, 508]
primes below 20000 from the master: 2262
same as one loop: True
- Verdict: stdlib.
Executors.newFixedThreadPoolandinvokeAll, which returns the futures when all the parts are done.
using System;
using System.Linq;
using System.Threading.Tasks;
class Program
{
const int Limit = 20000;
const int Workers = 4;
// The work of one worker: count the primes in [lo, hi).
static int CountPrimes(int lo, int hi)
{
int count = 0;
for (int n = Math.Max(lo, 2); n < hi; n++)
{
int d = 2;
while (d * d <= n && n % d != 0) d++;
if (d * d > n) count++;
}
return count;
}
static void Main()
{
// 1. Split the work into one part for each worker.
var parts = Enumerable.Range(0, Workers)
.Select(i => (Lo: Limit * i / Workers, Hi: Limit * (i + 1) / Workers))
.ToArray();
// 2. Start a task for each part, then wait for all of them.
var tasks = parts.Select(p => Task.Run(() => CountPrimes(p.Lo, p.Hi))).ToArray();
int[] results = Task.WhenAll(tasks).Result;
// 3. Combine the partial results.
int total = results.Sum();
Console.WriteLine("parts: [" + string.Join(", ", parts.Select(p => $"({p.Lo}, {p.Hi})")) + "]");
Console.WriteLine("primes in each part: [" + string.Join(", ", results) + "]");
Console.WriteLine($"primes below {Limit} from the master: {total}");
Console.WriteLine("same as one loop: " + (total == CountPrimes(0, Limit) ? "True" : "False"));
}
}
parts: [(0, 5000), (5000, 10000), (10000, 15000), (15000, 20000)]
primes in each part: [669, 560, 525, 508]
primes below 20000 from the master: 2262
same as one loop: True
- Verdict: stdlib.
Task.Runfor each part andTask.WhenAllto collect the results in order.
const { Worker } = require("node:worker_threads");
const LIMIT = 20000;
const WORKERS = 4;
// The work of one worker: count the primes in [lo, hi).
function countPrimes(lo, hi) {
let count = 0;
for (let n = Math.max(lo, 2); n < hi; n++) {
let d = 2;
while (d * d <= n && n % d !== 0) d++;
if (d * d > n) count++;
}
return count;
}
// Each worker thread runs this code with its part and posts back its count.
const workerCode = `
const { parentPort, workerData } = require("node:worker_threads");
${countPrimes.toString()}
parentPort.postMessage(countPrimes(workerData.lo, workerData.hi));
`;
async function master(limit, workers) {
// 1. Split the work into one part for each worker.
const bounds = Array.from({ length: workers + 1 }, (_, i) => Math.floor((limit * i) / workers));
const parts = bounds.slice(0, -1).map((lo, i) => [lo, bounds[i + 1]]);
// 2. Start the workers, then wait for all of them.
const results = await Promise.all(
parts.map(
([lo, hi]) =>
new Promise((resolve, reject) => {
const w = new Worker(workerCode, { eval: true, workerData: { lo, hi } });
w.once("message", resolve);
w.once("error", reject);
}),
),
);
// 3. Combine the partial results.
return [parts, results, results.reduce((a, b) => a + b, 0)];
}
master(LIMIT, WORKERS).then(([parts, results, total]) => {
console.log("parts: [" + parts.map(([lo, hi]) => `(${lo}, ${hi})`).join(", ") + "]");
console.log("primes in each part: [" + results.join(", ") + "]");
console.log(`primes below ${LIMIT} from the master: ${total}`);
console.log("same as one loop: " + (total === countPrimes(0, LIMIT) ? "True" : "False"));
});
parts: [(0, 5000), (5000, 10000), (10000, 15000), (15000, 20000)]
primes in each part: [669, 560, 525, 508]
primes below 20000 from the master: 2262
same as one loop: True
- Verdict: stdlib.
node:worker_threadsruns each part in its own thread withworkerData, andPromise.allwaits for everymessage.
import { Worker } from "node:worker_threads";
const LIMIT = 20000;
const WORKERS = 4;
// The work of one worker: count the primes in [lo, hi).
function countPrimes(lo: number, hi: number): number {
let count = 0;
for (let n = Math.max(lo, 2); n < hi; n++) {
let d = 2;
while (d * d <= n && n % d !== 0) d++;
if (d * d > n) count++;
}
return count;
}
// Each worker thread runs this code with its part and posts back its count.
const workerCode = `
const { parentPort, workerData } = require("node:worker_threads");
${countPrimes.toString().replace(/: number/g, "")}
parentPort.postMessage(countPrimes(workerData.lo, workerData.hi));
`;
async function master(limit: number, workers: number): Promise<[number[][], number[], number]> {
// 1. Split the work into one part for each worker.
const bounds = Array.from({ length: workers + 1 }, (_, i) => Math.floor((limit * i) / workers));
const parts: number[][] = bounds.slice(0, -1).map((lo, i) => [lo, bounds[i + 1]]);
// 2. Start the workers, then wait for all of them.
const results = await Promise.all(
parts.map(
([lo, hi]) =>
new Promise<number>((resolve, reject) => {
const w = new Worker(workerCode, { eval: true, workerData: { lo, hi } });
w.once("message", resolve);
w.once("error", reject);
}),
),
);
// 3. Combine the partial results.
return [parts, results, results.reduce((a, b) => a + b, 0)];
}
master(LIMIT, WORKERS).then(([parts, results, total]) => {
console.log("parts: [" + parts.map(([lo, hi]) => `(${lo}, ${hi})`).join(", ") + "]");
console.log("primes in each part: [" + results.join(", ") + "]");
console.log(`primes below ${LIMIT} from the master: ${total}`);
console.log("same as one loop: " + (total === countPrimes(0, LIMIT) ? "True" : "False"));
});
parts: [(0, 5000), (5000, 10000), (10000, 15000), (15000, 20000)]
primes in each part: [669, 560, 525, 508]
primes below 20000 from the master: 2262
same as one loop: True
- Verdict: stdlib. The same
node:worker_threadsprogram with types. The worker code is a string of plain JavaScript.
package main
import (
"fmt"
"strings"
"sync"
)
const (
limit = 20000
workers = 4
)
// countPrimes is the work of one worker: it counts the primes in [lo, hi).
func countPrimes(lo, hi int) int {
count := 0
if lo < 2 {
lo = 2
}
for n := lo; n < hi; n++ {
d := 2
for d*d <= n && n%d != 0 {
d++
}
if d*d > n {
count++
}
}
return count
}
func main() {
// 1. Split the work into one part for each worker.
parts := make([][2]int, workers)
for i := range parts {
parts[i] = [2]int{limit * i / workers, limit * (i + 1) / workers}
}
// 2. Start the workers, then wait for all of them.
results := make([]int, workers) // each worker writes only its own slot
var wg sync.WaitGroup
for i, p := range parts {
wg.Add(1)
go func(i int, p [2]int) {
defer wg.Done()
results[i] = countPrimes(p[0], p[1])
}(i, p)
}
wg.Wait()
// 3. Combine the partial results.
total := 0
for _, r := range results {
total += r
}
shown := make([]string, len(parts))
for i, p := range parts {
shown[i] = fmt.Sprintf("(%d, %d)", p[0], p[1])
}
nums := make([]string, len(results))
for i, r := range results {
nums[i] = fmt.Sprint(r)
}
fmt.Println("parts: [" + strings.Join(shown, ", ") + "]")
fmt.Println("primes in each part: [" + strings.Join(nums, ", ") + "]")
fmt.Printf("primes below %d from the master: %d\n", limit, total)
if total == countPrimes(0, limit) {
fmt.Println("same as one loop: True")
} else {
fmt.Println("same as one loop: False")
}
}
parts: [(0, 5000), (5000, 10000), (10000, 15000), (15000, 20000)]
primes in each part: [669, 560, 525, 508]
primes below 20000 from the master: 2262
same as one loop: True
- Verdict: native. A goroutine for each part writes its own slot, and a
sync.WaitGroupmakes the master wait.
use std::thread;
const LIMIT: u32 = 20000;
const WORKERS: u32 = 4;
// The work of one worker: count the primes in [lo, hi).
fn count_primes(lo: u32, hi: u32) -> u32 {
let mut count = 0;
for n in lo.max(2)..hi {
let mut d = 2;
while d * d <= n && n % d != 0 {
d += 1;
}
if d * d > n {
count += 1;
}
}
count
}
fn main() {
// 1. Split the work into one part for each worker.
let parts: Vec<(u32, u32)> = (0..WORKERS)
.map(|i| (LIMIT * i / WORKERS, LIMIT * (i + 1) / WORKERS))
.collect();
// 2. Start the workers in a scope; the scope waits for all of them.
let results: Vec<u32> = thread::scope(|s| {
let handles: Vec<_> = parts
.iter()
.map(|&(lo, hi)| s.spawn(move || count_primes(lo, hi)))
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
// 3. Combine the partial results.
let total: u32 = results.iter().sum();
let shown: Vec<String> = parts.iter().map(|(lo, hi)| format!("({}, {})", lo, hi)).collect();
println!("parts: [{}]", shown.join(", "));
println!("primes in each part: {:?}", results);
println!("primes below {} from the master: {}", LIMIT, total);
println!("same as one loop: {}", if total == count_primes(0, LIMIT) { "True" } else { "False" });
}
parts: [(0, 5000), (5000, 10000), (10000, 15000), (15000, 20000)]
primes in each part: [669, 560, 525, 508]
primes below 20000 from the master: 2262
same as one loop: True
- Verdict: stdlib.
std::thread::scopelets the workers borrow the parts, and the scope ends only when every worker has joined.
Consequences
Benefits:
- The workers are exchangeable and extensible.1 The master can use more workers without a change to the worker code.
- The code of the client and the workers is separate from the code that splits the work.1 Only the master knows how the job is split and combined.
- The pattern allows parallel computing, because all the workers can work at the same time.1
Liabilities:
- The job must split into parts that are independent. If the parts depend on each other, the workers must communicate, and the master is no longer enough.
- The master must split the job correctly and wait for every worker. A part that the split misses, or a result that the master reads too early, gives a wrong result with no error.
- Equal parts do not always take equal time. In the example, a part with larger numbers needs more trial divisions, so the master waits for the slowest worker.
- Splitting, starting the workers and combining the results take time. For a small job, one loop is faster.
In this program, the master splits 1002 items into four parts of 1002 // 4 items, so two items are in no part:
This code runs but gives a wrong answer on purpose.
import threading
items = list(range(1, 1003)) # 1002 numbers to add up
WORKERS = 4
# Wrong: each part has len // WORKERS items, so the last 1002 % 4 items are in no part.
size = len(items) // WORKERS
parts = [items[i * size:(i + 1) * size] for i in range(WORKERS)]
results = [0] * WORKERS
def worker(i):
results[i] = sum(parts[i])
threads = [threading.Thread(target=worker, args=(i,)) for i in range(WORKERS)]
for t in threads:
t.start()
for t in threads:
t.join()
print("items in the parts:", sum(len(p) for p in parts), "of", len(items))
print("total from the master:", sum(results))
print("right total:", sum(items))
items in the parts: 1000 of 1002
total from the master: 500500
right total: 502503
The bounds n * i // workers in the example cover every item, because the last bound is n itself.
When not to use it
Do not use master-worker when the parts depend on each other, or when the parts appear over time instead of all at the start. A work queue fits tasks that arrive over time, and a pipeline fits work that goes through fixed steps. Do not use it for a job that is cheap, because the threads cost more than they save. When the parts split again into smaller parts, fork-join is the general form.
Variants and related patterns
- More parts than workers. The master splits the job into many small parts and gives the next part to a worker when the worker is free, so a slow part does not hold up the others. Python's
Pool.mapchops the iterable into a number of chunks which it submits to the pool as separate tasks.4 AThreadPoolis fully interface compatible withPool, with worker threads in place of processes.4
import threading
from multiprocessing.pool import ThreadPool
seen = set() # the worker threads that did a part
lock = threading.Lock()
def square_sum(part):
with lock:
seen.add(threading.get_ident())
return sum(n * n for n in part)
items = range(1, 1003)
parts = [items[i:i + 50] for i in range(0, len(items), 50)] # more parts than workers
with ThreadPool(4) as pool:
results = pool.map(square_sum, parts) # a free worker takes the next part
print("parts:", len(parts))
print("worker threads that did a part, at most 4:", len(seen) <= 4)
print("total from the master:", sum(results))
print("same as one loop:", sum(results) == sum(n * n for n in items))
parts: 21
worker threads that did a part, at most 4: True
total from the master: 335839505
same as one loop: True
- Futures for the results. Java's
ExecutorService.invokeAllexecutes the given tasks and returns a list of futures that hold their status and results when all complete.5 The master then reads each future. - Fork-join lets a worker split its part again and join the results of its sub-parts. Master-worker splits once, at the master.
- Thread pool is the usual way to keep the workers. The master sends the parts to the pool instead of starting a thread for each part.
- Barrier replaces the join when the workers run several steps and must wait for each other between steps.
Known uses
- Python:
multiprocessing.Poolparallelizes the execution of a function across multiple input values, distributing the input data across processes.4 - Java:
ExecutorService.invokeAllruns a collection of tasks and waits for all of them to complete.5 - Terminology: in 2018, Python switched to main, parent or server in place of master, and to worker, child or helper in place of slave, depending on context.3
References
- Examples to Accompany: Design Patterns, Elements of Reusable Object-Oriented Software, AG Communication Systems, 1999, Master-Slave, page A-45
- Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad and Michael Stal, Pattern-Oriented Software Architecture, Volume 1: A System of Patterns, John Wiley and Sons, Master-Slave
- Master–slave (technology), Wikipedia, lead; Controversy, Notable events
- multiprocessing, Process-based parallelism, Python documentation, Introduction; Pool.map; ThreadPool
- Interface ExecutorService, Java SE 21 API, the interface description; invokeAll
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 2J1DHE Edit this page History Report an error Markdown