Programming Search⌘K

Conceptcore

Concurrency pattern

Also called concurrency patterns, concurrency design pattern, patterns for concurrent objects, synchronization pattern.

A concurrency pattern is a design pattern for work that runs at the same time. Each one answers the same question: which code may touch which state, and when.

Applies to
core-languages

Idea

When two pieces of work run at the same time, they can touch the same state. A read by one thread and a write by another can interleave in an order that the programmer did not expect, and the result is wrong only sometimes. Wikipedia describes a concurrency pattern as a design pattern that supports concurrent processing.1 Each pattern of this sub-area gives a fixed answer to one question: which code may touch which state, and when.

There are three basic answers. Guard the shared state with a lock. Give the state to one owner, and let the others send it messages. Or do not share the state at all: each piece of work makes its own result, and one place combines the results. The first and the third answer are in this program:

import threading
from concurrent.futures import ThreadPoolExecutor

total = 0
lock = threading.Lock()


def add_shared(n):  # every task writes the same variable, so a lock guards it
    global total
    for _ in range(n):
        with lock:
            total += 1


def count_own(n):  # every task returns its own result, so nothing is shared
    return sum(1 for _ in range(n))


with ThreadPoolExecutor(max_workers=4) as pool:
    list(pool.map(add_shared, [1000] * 4))
    results = list(pool.map(count_own, [1000] * 4))

print("shared variable with a lock:", total)
print("own results, combined by the caller:", sum(results))
Output
shared variable with a lock: 4000
own results, combined by the caller: 4000

How it works

A concurrency pattern names the parts of the program that run at the same time, the state that each part may use, and the rule that keeps the use safe. The rule is usually one of the three answers above, or a mix of them.

POSA2 presents 17 interrelated patterns for concurrent and networked software, and it puts them in groups.2 Three of its groups are about concurrency:

Group Problem Patterns
Event handling one thread must react to many sources of events Reactor, Proactor, Asynchronous Completion Token, Acceptor-Connector
Synchronization shared objects must stay correct when threads call them Scoped Locking, Strategized Locking, Thread-Safe Interface, Double-Checked Locking
Concurrency the program must decide which threads exist and what each one does Active Object, Monitor Object, Half-Sync/Half-Async, Leader/Followers, Thread-Specific Storage

Other patterns in this sub-area come from other sources. Wikipedia also lists balking, barrier, guarded suspension, the readers-writer lock, the scheduler, the thread pool and thread-local storage.1 Producer-consumer, Thread pool, Fork/Join and Master-worker divide work among threads. Immutable object, Copy-on-write and Thread confinement remove the sharing, so that no lock is needed.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaNative
CIdiomThreads, mutexes and condition variables come from a library, such as the optional threads.h of C11 or POSIX threads, and the programmer must keep the rules of each pattern by hand.
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinIdiomThe JVM threads, locks and queues of Java are available, and suspend functions with a coroutine library add channels and structured concurrency; no example is executed here because the test image has no kotlinc.
SQLIdiomThe database runs concurrent sessions, and transactions, isolation levels and row locks keep their updates correct; the program does not create threads.
BashIdiomA command with & runs as a separate process and wait joins it; processes share no memory, so they exchange data through pipes and files.
PowerShellIdiomThread jobs and parallel loops run script blocks at the same time, and the .NET locks and concurrent collections are available; no example is executed here because the test image has no pwsh.
HTMLDoes not applyMarkup has no threads or shared state; workers are started and used from JavaScript.
CSSDoes not applyStyle rules have no threads or shared state.
Regular expressionsDoes not applyA pattern has no threads or shared state.
Language Verdict Mechanism
Python idiom threading.Lock and Condition; queue.Queue for messages; asyncio for an event loop; the GIL in CPython
JavaScript native one thread for each agent; an event loop; each job runs to completion; workers that share nothing by default
TypeScript native the model of JavaScript, with types for promises and messages
Java native synchronized methods and blocks; wait and notify; the java.util.concurrent package
Kotlin idiom the threads and locks of the JVM; suspend functions with a coroutine library
C# native the lock statement; async and await; concurrent collections and BlockingCollection
Go native goroutines, channels and select; sync.Mutex and sync.WaitGroup
Rust native the Send and Sync traits, checked by the compiler; Mutex, channels and scoped threads in std
C idiom a thread library such as POSIX threads; mutexes and condition variables
C++ idiom std::thread, std::mutex, std::condition_variable and std::atomic in the standard library
Bash idiom background processes with & and wait; pipes between processes
PowerShell idiom thread jobs and parallel loops; the locks and collections of .NET
SQL idiom transactions, isolation levels and row locks for concurrent sessions
Regex n/a a pattern has no threads or shared state
HTML n/a markup has no threads or shared state
CSS n/a style rules have no threads or shared state

The languages differ in which answer they make easy. Go prefers the second answer. Effective Go reduces it to a slogan: "Do not communicate by sharing memory; instead, share memory by communicating."3 When a value goes through a channel, only one goroutine has access to the value at any given time.3 The same text says that this approach can be taken too far, and that a reference count may be best done with a mutex around an integer.3

Rust checks the rules when it compiles the program. Its book calls this fearless concurrency, and it covers message-passing concurrency and shared-state concurrency as two separate topics.4 The Send trait marks a type whose values can be transferred to another thread, and Sync marks a type that is safe to reference from several threads.5 The compiler rejects a program that moves a value to another thread when the type of the value is not Send.

In CPython, the Global Interpreter Lock lets only one thread execute Python code at once.6 This does not make a read followed by a write safe, as the Pitfalls section shows. Java collects its tools in java.util.concurrent, which it describes as "Utility classes commonly useful in concurrent programming." The package has synchronizers and concurrent collections.7 JavaScript avoids the problem in a different way. An agent runs one job at a time, and each job is processed completely before any other job is processed.8 A task that waits between a read and a write can still lose an update.

The example files show the three answers in each language: a lock around a shared counter, one owner thread that receives messages, and a result for each thread that is combined after the join.

PythonGitHub
import queue
import threading

THREADS = 4
STEPS = 1000


def run_threads(target):
    threads = [threading.Thread(target=target, args=(i,)) for i in range(THREADS)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()


# 1. Synchronization: a lock guards the shared counter.
count = 0
lock = threading.Lock()


def add_with_lock(_):
    global count
    for _ in range(STEPS):
        with lock:
            count += 1


run_threads(add_with_lock)
print("lock around a shared counter:", count)

# 2. Confinement: one owner thread keeps the counter; the others send it messages.
inbox = queue.Queue()
owned = []


def owner():
    total = 0
    for _ in range(THREADS * STEPS):
        total += inbox.get(timeout=5)
    owned.append(total)


keeper = threading.Thread(target=owner)
keeper.start()
run_threads(lambda _: [inbox.put(1) for _ in range(STEPS)])
keeper.join()
print("one owner thread, the others send messages:", owned[0])

# 3. No sharing: each thread makes its own result, and the results are combined after the join.
parts = [0] * THREADS


def add_own(i):
    for _ in range(STEPS):
        parts[i] += 1  # only thread i writes slot i


run_threads(add_own)
print("own result for each thread, combined after the join:", sum(parts))
Output
lock around a shared counter: 4000
one owner thread, the others send messages: 4000
own result for each thread, combined after the join: 4000
  • Verdict: idiom. threading.Lock for the shared counter, queue.Queue for the messages to the owner thread, and a list slot for each thread. In CPython the GIL lets only one thread run Python code at a time, but a read and a later write can still lose an update.
#include <condition_variable>
#include <deque>
#include <functional>
#include <iostream>
#include <mutex>
#include <numeric>
#include <thread>
#include <vector>

constexpr int kThreads = 4;
constexpr int kSteps = 1000;

void run_threads(const std::function<void(int)>& body) {
    std::vector<std::thread> threads;
    for (int i = 0; i < kThreads; i++) threads.emplace_back(body, i);
    for (auto& t : threads) t.join();
}

int main() {
    // 1. Synchronization: a mutex guards the shared counter.
    int count = 0;
    std::mutex m;
    run_threads([&](int) {
        for (int n = 0; n < kSteps; n++) {
            std::lock_guard<std::mutex> lk(m);
            count++;
        }
    });
    std::cout << "lock around a shared counter: " << count << "\n";

    // 2. Confinement: one owner thread keeps the counter; the others send it messages.
    std::mutex qm;
    std::condition_variable cv;
    std::deque<int> inbox;
    int owned = 0;
    std::thread owner([&] {
        int total = 0;
        for (int n = 0; n < kThreads * kSteps; n++) {
            std::unique_lock<std::mutex> lk(qm);
            cv.wait(lk, [&] { return !inbox.empty(); });
            total += inbox.front();
            inbox.pop_front();
        }
        owned = total;
    });
    run_threads([&](int) {
        for (int n = 0; n < kSteps; n++) {
            {
                std::lock_guard<std::mutex> lk(qm);
                inbox.push_back(1);
            }
            cv.notify_one();
        }
    });
    owner.join();  // join makes the owner's write visible here
    std::cout << "one owner thread, the others send messages: " << owned << "\n";

    // 3. No sharing: each thread makes its own result, and the results are combined after the join.
    std::vector<int> parts(kThreads, 0);
    run_threads([&](int i) {
        for (int n = 0; n < kSteps; n++) parts[i]++;  // only thread i writes slot i
    });
    std::cout << "own result for each thread, combined after the join: "
              << std::accumulate(parts.begin(), parts.end(), 0) << "\n";
}
Output
lock around a shared counter: 4000
one owner thread, the others send messages: 4000
own result for each thread, combined after the join: 4000
  • Verdict: idiom. std::mutex with std::lock_guard, a queue that a mutex and a std::condition_variable protect, and a std::vector slot for each thread.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.IntConsumer;

public class Main {
    static final int THREADS = 4;
    static final int STEPS = 1000;

    static void runThreads(IntConsumer body) throws InterruptedException {
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < THREADS; i++) {
            int id = i;
            threads.add(new Thread(() -> body.accept(id)));
        }
        for (Thread t : threads) t.start();
        for (Thread t : threads) t.join();
    }

    static int count = 0;

    public static void main(String[] args) throws Exception {
        // 1. Synchronization: a lock guards the shared counter.
        ReentrantLock lock = new ReentrantLock();
        runThreads(i -> {
            for (int n = 0; n < STEPS; n++) {
                lock.lock();
                try {
                    count++;
                } finally {
                    lock.unlock();
                }
            }
        });
        System.out.println("lock around a shared counter: " + count);

        // 2. Confinement: one owner thread keeps the counter; the others send it messages.
        BlockingQueue<Integer> inbox = new LinkedBlockingQueue<>();
        int[] owned = new int[1];
        Thread owner = new Thread(() -> {
            int total = 0;
            try {
                for (int n = 0; n < THREADS * STEPS; n++) total += inbox.poll(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            owned[0] = total;
        });
        owner.start();
        runThreads(i -> {
            for (int n = 0; n < STEPS; n++) inbox.add(1);
        });
        owner.join(); // join makes the owner's write visible here
        System.out.println("one owner thread, the others send messages: " + owned[0]);

        // 3. No sharing: each thread makes its own result, and the results are combined after the join.
        int[] parts = new int[THREADS];
        runThreads(i -> {
            for (int n = 0; n < STEPS; n++) parts[i]++; // only thread i writes slot i
        });
        int sum = 0;
        for (int p : parts) sum += p;
        System.out.println("own result for each thread, combined after the join: " + sum);
    }
}
Output
lock around a shared counter: 4000
one owner thread, the others send messages: 4000
own result for each thread, combined after the join: 4000
  • Verdict: native. A ReentrantLock from java.util.concurrent.locks, a LinkedBlockingQueue for the messages, and an array slot for each thread. join makes the writes of a thread visible to the thread that joins it.
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;

class Program
{
    const int Threads = 4;
    const int Steps = 1000;

    static void RunThreads(Action<int> body)
    {
        var threads = Enumerable.Range(0, Threads).Select(i => new Thread(() => body(i))).ToList();
        foreach (var t in threads) t.Start();
        foreach (var t in threads) t.Join();
    }

    static void Main()
    {
        // 1. Synchronization: a lock guards the shared counter.
        int count = 0;
        var gate = new object();
        RunThreads(_ =>
        {
            for (int n = 0; n < Steps; n++)
                lock (gate) count++;
        });
        Console.WriteLine("lock around a shared counter: " + count);

        // 2. Confinement: one owner thread keeps the counter; the others send it messages.
        var inbox = new BlockingCollection<int>();
        int owned = 0;
        var owner = new Thread(() =>
        {
            int total = 0;
            for (int n = 0; n < Threads * Steps; n++) total += inbox.Take();
            owned = total;
        });
        owner.Start();
        RunThreads(_ =>
        {
            for (int n = 0; n < Steps; n++) inbox.Add(1);
        });
        owner.Join();
        Console.WriteLine("one owner thread, the others send messages: " + owned);

        // 3. No sharing: each thread makes its own result, and the results are combined after the join.
        var parts = new int[Threads];
        RunThreads(i =>
        {
            for (int n = 0; n < Steps; n++) parts[i]++; // only thread i writes slot i
        });
        Console.WriteLine("own result for each thread, combined after the join: " + parts.Sum());
    }
}
Output
lock around a shared counter: 4000
one owner thread, the others send messages: 4000
own result for each thread, combined after the join: 4000
  • Verdict: native. The lock statement guards the counter, a BlockingCollection<int> carries the messages, and each thread writes its own array slot.
JavaScriptGitHub
// JavaScript runs these tasks on one thread, so they can interleave only at an await.
const TASKS = 4;
const STEPS = 1000;
const tick = () => new Promise((resolve) => setImmediate(resolve));

// A lock for async tasks: lock() waits until no other task holds it.
class Mutex {
  constructor() {
    this.held = false;
    this.waiters = [];
  }
  async lock() {
    while (this.held) await new Promise((resolve) => this.waiters.push(resolve));
    this.held = true;
  }
  unlock() {
    this.held = false;
    const next = this.waiters.shift();
    if (next) next();
  }
}

// A channel with no bound: receive() waits until a value is there.
class Channel {
  constructor() {
    this.values = [];
    this.waiters = [];
  }
  send(value) {
    const next = this.waiters.shift();
    if (next) next(value);
    else this.values.push(value);
  }
  receive() {
    if (this.values.length > 0) return Promise.resolve(this.values.shift());
    return new Promise((resolve) => this.waiters.push(resolve));
  }
}

const runTasks = (task) => Promise.all(Array.from({ length: TASKS }, (_, i) => task(i)));

async function main() {
  // 1. Synchronization: a lock guards the shared counter across the await.
  let count = 0;
  const mutex = new Mutex();
  await runTasks(async () => {
    for (let n = 0; n < STEPS; n++) {
      await mutex.lock();
      const value = count;
      await tick(); // other tasks run here, but they wait for the lock
      count = value + 1;
      mutex.unlock();
    }
  });
  console.log("lock around a shared counter: " + count);

  // 2. Confinement: one owner task keeps the counter; the others send it messages.
  const inbox = new Channel();
  const owner = (async () => {
    let total = 0;
    for (let n = 0; n < TASKS * STEPS; n++) total += await inbox.receive();
    return total;
  })();
  await runTasks(async () => {
    for (let n = 0; n < STEPS; n++) {
      inbox.send(1);
      await tick();
    }
  });
  console.log("one owner thread, the others send messages: " + (await owner));

  // 3. No sharing: each task makes its own result, and the results are combined at the end.
  const parts = new Array(TASKS).fill(0);
  await runTasks(async (i) => {
    for (let n = 0; n < STEPS; n++) {
      parts[i] += 1; // only task i writes slot i
      if (n % 100 === 0) await tick();
    }
  });
  console.log("own result for each thread, combined after the join: " + parts.reduce((a, b) => a + b, 0));
}

main();
Output
lock around a shared counter: 4000
one owner thread, the others send messages: 4000
own result for each thread, combined after the join: 4000
  • Verdict: native. The tasks run on one thread, and each job runs to completion. A lock and a channel are still needed when a task waits between a read and a write, so the example builds a small async mutex and a channel with promises.
TypeScriptGitHub
// JavaScript runs these tasks on one thread, so they can interleave only at an await.
const TASKS = 4;
const STEPS = 1000;
const tick = (): Promise<void> => new Promise((resolve) => setImmediate(resolve));

// A lock for async tasks: lock() waits until no other task holds it.
class Mutex {
  private held = false;
  private waiters: (() => void)[] = [];

  async lock(): Promise<void> {
    while (this.held) await new Promise<void>((resolve) => this.waiters.push(resolve));
    this.held = true;
  }
  unlock(): void {
    this.held = false;
    const next = this.waiters.shift();
    if (next) next();
  }
}

// A channel with no bound: receive() waits until a value is there.
class Channel<T> {
  private values: T[] = [];
  private waiters: ((value: T) => void)[] = [];

  send(value: T): void {
    const next = this.waiters.shift();
    if (next) next(value);
    else this.values.push(value);
  }
  receive(): Promise<T> {
    if (this.values.length > 0) return Promise.resolve(this.values.shift()!);
    return new Promise<T>((resolve) => this.waiters.push(resolve));
  }
}

const runTasks = (task: (i: number) => Promise<void>): Promise<void[]> => Promise.all(Array.from({ length: TASKS }, (_, i) => task(i)));

async function main(): Promise<void> {
  // 1. Synchronization: a lock guards the shared counter across the await.
  let count = 0;
  const mutex = new Mutex();
  await runTasks(async () => {
    for (let n = 0; n < STEPS; n++) {
      await mutex.lock();
      const value = count;
      await tick(); // other tasks run here, but they wait for the lock
      count = value + 1;
      mutex.unlock();
    }
  });
  console.log("lock around a shared counter: " + count);

  // 2. Confinement: one owner task keeps the counter; the others send it messages.
  const inbox = new Channel<number>();
  const owner = (async () => {
    let total = 0;
    for (let n = 0; n < TASKS * STEPS; n++) total += await inbox.receive();
    return total;
  })();
  await runTasks(async () => {
    for (let n = 0; n < STEPS; n++) {
      inbox.send(1);
      await tick();
    }
  });
  console.log("one owner thread, the others send messages: " + (await owner));

  // 3. No sharing: each task makes its own result, and the results are combined at the end.
  const parts: number[] = new Array(TASKS).fill(0);
  await runTasks(async (i) => {
    for (let n = 0; n < STEPS; n++) {
      parts[i] += 1; // only task i writes slot i
      if (n % 100 === 0) await tick();
    }
  });
  console.log("own result for each thread, combined after the join: " + parts.reduce((a, b) => a + b, 0));
}

main();
Output
lock around a shared counter: 4000
one owner thread, the others send messages: 4000
own result for each thread, combined after the join: 4000
  • Verdict: native. The same program as JavaScript, with types for the mutex, the channel and the tasks.
package main

import (
	"fmt"
	"sync"
)

const (
	goroutines = 4
	steps      = 1000
)

func runAll(body func(i int)) {
	var wg sync.WaitGroup
	for i := 0; i < goroutines; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			body(i)
		}(i)
	}
	wg.Wait()
}

func main() {
	// 1. Synchronization: a mutex guards the shared counter.
	count := 0
	var mu sync.Mutex
	runAll(func(int) {
		for n := 0; n < steps; n++ {
			mu.Lock()
			count++
			mu.Unlock()
		}
	})
	fmt.Println("lock around a shared counter:", count)

	// 2. Confinement: one owner goroutine keeps the counter; the others send it messages.
	inbox := make(chan int)
	owned := make(chan int)
	go func() {
		total := 0
		for n := 0; n < goroutines*steps; n++ {
			total += <-inbox
		}
		owned <- total
	}()
	runAll(func(int) {
		for n := 0; n < steps; n++ {
			inbox <- 1
		}
	})
	fmt.Println("one owner thread, the others send messages:", <-owned)

	// 3. No sharing: each goroutine makes its own result, and the results are combined after the wait.
	parts := make([]int, goroutines)
	runAll(func(i int) {
		for n := 0; n < steps; n++ {
			parts[i]++ // only goroutine i writes slot i
		}
	})
	sum := 0
	for _, p := range parts {
		sum += p
	}
	fmt.Println("own result for each thread, combined after the join:", sum)
}
Output
lock around a shared counter: 4000
one owner thread, the others send messages: 4000
own result for each thread, combined after the join: 4000
  • Verdict: native. A sync.Mutex for the shared counter, an unbuffered channel to the owner goroutine, and a slice slot for each goroutine, with a sync.WaitGroup for the join.
RustGitHub
use std::sync::mpsc;
use std::sync::Mutex;
use std::thread;

const THREADS: usize = 4;
const STEPS: usize = 1000;

fn main() {
    // 1. Synchronization: a mutex owns the shared counter; the type system requires the lock.
    let count = Mutex::new(0);
    thread::scope(|s| {
        for _ in 0..THREADS {
            s.spawn(|| {
                for _ in 0..STEPS {
                    *count.lock().unwrap() += 1;
                }
            });
        }
    });
    println!("lock around a shared counter: {}", count.into_inner().unwrap());

    // 2. Confinement: one owner thread keeps the counter; the others send it messages.
    let (tx, rx) = mpsc::channel();
    let owner = thread::spawn(move || rx.iter().sum::<usize>()); // ends when all senders are gone
    thread::scope(|s| {
        for _ in 0..THREADS {
            let tx = tx.clone();
            s.spawn(move || {
                for _ in 0..STEPS {
                    tx.send(1).unwrap();
                }
            });
        }
    });
    drop(tx);
    println!("one owner thread, the others send messages: {}", owner.join().unwrap());

    // 3. No sharing: each thread gets its own slot, and the results are combined after the join.
    let mut parts = vec![0usize; THREADS];
    thread::scope(|s| {
        for part in parts.iter_mut() {
            s.spawn(move || {
                for _ in 0..STEPS {
                    *part += 1; // this thread has the only mutable reference to its slot
                }
            });
        }
    });
    println!("own result for each thread, combined after the join: {}", parts.iter().sum::<usize>());
}
Output
lock around a shared counter: 4000
one owner thread, the others send messages: 4000
own result for each thread, combined after the join: 4000
  • Verdict: native. The counter lives inside a Mutex, so it cannot be changed without the lock. An mpsc channel moves the messages to the owner thread, and iter_mut gives each scoped thread the only mutable reference to its slot.
  • Lock-free and atomic designs. An atomic operation changes one value without a lock. See Atomic operations and memory models. It removes waiting, but it is hard to extend to more than one value.
  • Event-driven designs. An event loop runs many tasks on one thread. The tasks take turns, so most state needs no lock. See Reactor and Event loop.
  • Message passing between processes. When the parts do not share memory, every exchange is a message. See Message passing and Channel.
  • Distributed patterns. Some of the same ideas, such as a queue between producers and workers, also work between machines. Then the messages can be lost or repeated, and the patterns must also handle failure.

Pitfalls

  • Check, then act. A thread reads a value, and then it writes a new value that depends on the read. Another thread can write between the two steps, and one update is lost:

This code runs but gives a wrong answer on purpose.

import threading
import time

count = 0


def add(_):
    global count
    for _ in range(100):
        value = count  # read
        time.sleep(0.001)  # another thread can run between the read and the write
        count = value + 1  # write: an update of another thread can be lost


threads = [threading.Thread(target=add, args=(i,)) for i in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("expected:", 4 * 100)
print("updates lost:", count < 400)
Output
expected: 400
updates lost: True

The read and the write must be one step: put both inside one lock, give the counter to one owner, or give each thread its own counter. The three answers are in the example files.

  • Locks in the wrong order. Two threads that take two locks in different orders can wait for each other for ever. See Deadlock.
  • A lock that is too wide. A lock around slow work, such as I/O, makes the other threads wait, and the program runs as if it had one thread.
  • Forgotten sharing. A data race happens when two threads access one location, at least one access is a write, and nothing orders them. See Data race.

Cost

A lock costs time each time that a thread takes it, and more when threads must wait for each other. A message costs a copy or a move and a queue operation. A result for each thread costs memory for each thread and one step to combine the results. A design that shares less state usually needs fewer locks and scales better, but it can need more memory and more copies. The largest cost is often in the design: a pattern that is easy to check by reading the code prevents bugs that tests find only sometimes.

History

The second volume of the Pattern-Oriented Software Architecture series, POSA2, was published by Wiley & Sons in 2000. Its authors are Douglas C. Schmidt, Michael Stal, Hans Rohnert and Frank Buschmann. POSA1 was published in 1996.2 POSA2 presents 17 patterns that address service access and configuration, event handling, synchronization and concurrency.2 The list of concurrency patterns in Wikipedia also has patterns that are not in POSA2, such as balking, the barrier and the thread pool.1

References

  1. Concurrency pattern, Wikipedia, Introduction; Examples
  2. Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Overview, the 17 patterns; Table of Contents, chapters 2 to 5
  3. Effective Go, Concurrency, Share by communicating
  4. The Rust Programming Language, 16 Fearless Concurrency, introduction
  5. The Rust Programming Language, 16.4 Extensible Concurrency with Send and Sync, Transferring Ownership Between Threads; Accessing from Multiple Threads
  6. threading, Thread-based parallelism, Python documentation, introduction, CPython implementation detail
  7. Package java.util.concurrent, Java SE 21 API, package description; Synchronizers; Concurrent Collections
  8. JavaScript execution model, MDN Web Docs, Job queue and event loop; Run-to-completion

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/ZN3FT7/text.yaml