Programming Search⌘K

Patternadvanced

Barrier synchronization

Also called barrier, barrier pattern, cyclic barrier, rendezvous of threads, phase barrier.

A barrier makes each thread of a group stop at one point until all the threads of the group arrive. Then all continue, so the work runs in phases and each phase sees the results of the last one.

Family
concurrency
Intent
Split a parallel computation into phases, and make sure that no thread starts the next phase until every thread has finished the current one.
Also called
Barrier, Rendezvous

Intent

A barrier for a group of threads or processes means that all of them stop at that point and do not proceed until all the others reach the barrier.1 A program puts barriers between the phases of a parallel computation, so that each phase starts only when the phase before it is complete.

Problem

Some parallel algorithms work in steps. In each step, every thread reads values that the other threads wrote in the step before, and then writes new values. If one thread writes before another thread has read, the reader sees a value from the wrong step. If one thread starts the next step early, it reads values that are not yet written. A lock on each value does not help, because the problem is not two writes at once but the order of the steps.

Solution

Give the group one barrier object that knows the number of parties. Each thread calls wait on the barrier at the end of a phase. The call blocks until all the threads have made their wait() calls, and then the threads are released simultaneously.2 The barrier can be used again for the next phase. A Java CyclicBarrier is called cyclic because it can be re-used after the waiting threads are released.3

 worker 0   worker 1   ...  worker 7
   read       read            read        phase 1: read the last step's values
 ───┴──────────┴───── barrier ──┴───      all 8 arrive, then all continue
   write      write           write       phase 2: write the new values
 ───┴──────────┴───── barrier ──┴───
   read       read            read        next step

A barrier can also run an action once per trip. A CyclicBarrier action runs after the last thread in the party arrives, but before any threads are released, which is useful for updating shared state before any of the parties continue.3

This structure is the base of the bulk synchronous parallel model. There, a computation proceeds in a series of global supersteps, and each superstep ends with a barrier synchronization: when a process reaches the barrier, it waits until all other processes have reached the same barrier.4

Example

Eight workers compute the prefix sums of the numbers 1 to 8. Worker i owns value i. In each of three steps, with the distances 1, 2 and 4, each worker reads the value that is that distance to its left, and then adds it to its own value. One barrier separates the reads from the writes, and a second barrier separates the writes from the next reads. The barrier action counts the trips: two per step.

input: [1, 2, 3, 4, 5, 6, 7, 8]
steps: 3
barrier trips: 6
prefix sums: [1, 3, 6, 10, 15, 21, 28, 36]
matches a running total: True

The examples for each language show the same program.

PythonGitHub
import threading

N = 8
values = list(range(1, N + 1))
distances = [1, 2, 4]  # each step adds the value that is d places to the left
print("input:", values)
trips = 0


def count_trip():
    global trips
    trips += 1  # runs once per trip, before the threads are released


barrier = threading.Barrier(N, action=count_trip, timeout=5)


def worker(i):
    for d in distances:
        # Phase 1: read a value that the last step wrote.
        add = values[i - d] if i >= d else 0
        barrier.wait()  # nobody writes until every worker has read
        # Phase 2: write the new value.
        values[i] += add
        barrier.wait()  # nobody reads until every worker has written


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

print("steps:", len(distances))
print("barrier trips:", trips)
print("prefix sums:", values)
print("matches a running total:", values == [sum(range(1, i + 2)) for i in range(N)])
Output
input: [1, 2, 3, 4, 5, 6, 7, 8]
steps: 3
barrier trips: 6
prefix sums: [1, 3, 6, 10, 15, 21, 28, 36]
matches a running total: True
  • Verdict: stdlib. threading.Barrier(parties, action=...) with wait(); the action runs once per trip.
#include <barrier>
#include <iostream>
#include <string>
#include <thread>
#include <vector>

constexpr int N = 8;
int values[N];
const std::vector<int> distances = {1, 2, 4};  // each step adds the value that is d places to the left

std::string show() {
    std::string s = "[";
    for (int i = 0; i < N; i++) s += (i ? ", " : "") + std::to_string(values[i]);
    return s + "]";
}

int main() {
    for (int i = 0; i < N; i++) values[i] = i + 1;
    std::cout << "input: " << show() << "\n";
    int trips = 0;
    // The completion function runs once per phase, before the threads are released.
    auto count_trip = [&]() noexcept { trips++; };
    std::barrier barrier(N, count_trip);

    std::vector<std::thread> threads;
    for (int i = 0; i < N; i++) {
        threads.emplace_back([&, i] {
            for (int d : distances) {
                // Phase 1: read a value that the last step wrote.
                int add = i >= d ? values[i - d] : 0;
                barrier.arrive_and_wait();  // nobody writes until every worker has read
                // Phase 2: write the new value.
                values[i] += add;
                barrier.arrive_and_wait();  // nobody reads until every worker has written
            }
        });
    }
    for (auto& t : threads) t.join();

    bool matches = true;
    for (int i = 0; i < N; i++) matches = matches && values[i] == (i + 1) * (i + 2) / 2;
    std::cout << "steps: " << distances.size() << "\n";
    std::cout << "barrier trips: " << trips << "\n";
    std::cout << "prefix sums: " << show() << "\n";
    std::cout << "matches a running total: " << (matches ? "True" : "False") << "\n";
}
Output
input: [1, 2, 3, 4, 5, 6, 7, 8]
steps: 3
barrier trips: 6
prefix sums: [1, 3, 6, 10, 15, 21, 28, 36]
matches a running total: True
  • Verdict: stdlib. std::barrier with a completion function and arrive_and_wait.
JavaGitHub
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static final int N = 8;
    static final int[] values = new int[N];
    static final int[] distances = {1, 2, 4}; // each step adds the value that is d places to the left

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < N; i++) values[i] = i + 1;
        System.out.println("input: " + Arrays.toString(values));
        AtomicInteger trips = new AtomicInteger();
        // The action runs once per trip, before the threads are released.
        CyclicBarrier barrier = new CyclicBarrier(N, trips::incrementAndGet);

        List<Thread> threads = new ArrayList<>();
        for (int w = 0; w < N; w++) {
            int i = w;
            threads.add(new Thread(() -> {
                try {
                    for (int d : distances) {
                        // Phase 1: read a value that the last step wrote.
                        int add = i >= d ? values[i - d] : 0;
                        barrier.await(5, TimeUnit.SECONDS); // nobody writes until every worker has read
                        // Phase 2: write the new value.
                        values[i] += add;
                        barrier.await(5, TimeUnit.SECONDS); // nobody reads until every worker has written
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }));
        }
        for (Thread t : threads) t.start();
        for (Thread t : threads) t.join();

        boolean matches = true;
        for (int i = 0; i < N; i++) matches &= values[i] == (i + 1) * (i + 2) / 2;
        System.out.println("steps: " + distances.length);
        System.out.println("barrier trips: " + trips.get());
        System.out.println("prefix sums: " + Arrays.toString(values));
        System.out.println("matches a running total: " + (matches ? "True" : "False"));
    }
}
Output
input: [1, 2, 3, 4, 5, 6, 7, 8]
steps: 3
barrier trips: 6
prefix sums: [1, 3, 6, 10, 15, 21, 28, 36]
matches a running total: True
  • Verdict: stdlib. CyclicBarrier(parties, barrierAction) with await; Phaser is the choice when the number of parties changes.
using System;
using System.Linq;
using System.Threading;

class Program
{
    const int N = 8;
    static readonly int[] values = Enumerable.Range(1, N).ToArray();
    static readonly int[] distances = { 1, 2, 4 }; // each step adds the value that is d places to the left

    static void Main()
    {
        Console.WriteLine("input: [" + string.Join(", ", values) + "]");
        int trips = 0;
        // The action runs once per phase, before the threads are released.
        using var barrier = new Barrier(N, b => trips++);

        var threads = Enumerable.Range(0, N).Select(i => new Thread(() =>
        {
            foreach (int d in distances)
            {
                // Phase 1: read a value that the last step wrote.
                int add = i >= d ? values[i - d] : 0;
                barrier.SignalAndWait(); // nobody writes until every worker has read
                // Phase 2: write the new value.
                values[i] += add;
                barrier.SignalAndWait(); // nobody reads until every worker has written
            }
        })).ToList();
        foreach (var t in threads) t.Start();
        foreach (var t in threads) t.Join();

        bool matches = Enumerable.Range(0, N).All(i => values[i] == (i + 1) * (i + 2) / 2);
        Console.WriteLine("steps: " + distances.Length);
        Console.WriteLine("barrier trips: " + trips);
        Console.WriteLine("prefix sums: [" + string.Join(", ", values) + "]");
        Console.WriteLine("matches a running total: " + (matches ? "True" : "False"));
    }
}
Output
input: [1, 2, 3, 4, 5, 6, 7, 8]
steps: 3
barrier trips: 6
prefix sums: [1, 3, 6, 10, 15, 21, 28, 36]
matches a running total: True
  • Verdict: stdlib. System.Threading.Barrier with a post-phase action and SignalAndWait.
JavaScriptGitHub
// A cyclic barrier for async tasks on one event loop.
class Barrier {
  constructor(parties, action) {
    this.parties = parties;
    this.action = action;
    this.waiting = []; // the resolve functions of the tasks that wait
  }

  wait() {
    return new Promise((resolve) => {
      this.waiting.push(resolve);
      if (this.waiting.length === this.parties) {
        this.action(); // runs once per trip, before the tasks are released
        const released = this.waiting;
        this.waiting = []; // the barrier can be used again
        released.forEach((r) => r());
      }
    });
  }
}

const N = 8;
const values = Array.from({ length: N }, (_, i) => i + 1);
const distances = [1, 2, 4]; // each step adds the value that is d places to the left
console.log("input: [" + values.join(", ") + "]");
let trips = 0;
const barrier = new Barrier(N, () => trips++);

async function worker(i) {
  for (const d of distances) {
    // Phase 1: read a value that the last step wrote.
    const add = i >= d ? values[i - d] : 0;
    await barrier.wait(); // nobody writes until every worker has read
    // Phase 2: write the new value.
    values[i] += add;
    await barrier.wait(); // nobody reads until every worker has written
  }
}

async function main() {
  await Promise.all(Array.from({ length: N }, (_, i) => worker(i)));
  const matches = values.every((v, i) => v === ((i + 1) * (i + 2)) / 2);
  console.log("steps:", distances.length);
  console.log("barrier trips:", trips);
  console.log("prefix sums: [" + values.join(", ") + "]");
  console.log("matches a running total:", matches ? "True" : "False");
}

main();
Output
input: [1, 2, 3, 4, 5, 6, 7, 8]
steps: 3
barrier trips: 6
prefix sums: [1, 3, 6, 10, 15, 21, 28, 36]
matches a running total: True
  • Verdict: idiom. The tasks share one thread, so the barrier is a list of resolve functions that the last task to arrive calls. It shows the phases, not parallel work.
TypeScriptGitHub
// A cyclic barrier for async tasks on one event loop.
class Barrier {
  parties: number;
  action: () => void;
  waiting: (() => void)[];

  constructor(parties: number, action: () => void) {
    this.parties = parties;
    this.action = action;
    this.waiting = []; // the resolve functions of the tasks that wait
  }

  wait(): Promise<void> {
    return new Promise<void>((resolve) => {
      this.waiting.push(resolve);
      if (this.waiting.length === this.parties) {
        this.action(); // runs once per trip, before the tasks are released
        const released = this.waiting;
        this.waiting = []; // the barrier can be used again
        released.forEach((r) => r());
      }
    });
  }
}

const N = 8;
const values: number[] = Array.from({ length: N }, (_, i) => i + 1);
const distances: number[] = [1, 2, 4]; // each step adds the value that is d places to the left
console.log("input: [" + values.join(", ") + "]");
let trips: number = 0;
const barrier = new Barrier(N, () => trips++);

async function worker(i: number): Promise<void> {
  for (const d of distances) {
    // Phase 1: read a value that the last step wrote.
    const add = i >= d ? values[i - d] : 0;
    await barrier.wait(); // nobody writes until every worker has read
    // Phase 2: write the new value.
    values[i] += add;
    await barrier.wait(); // nobody reads until every worker has written
  }
}

async function main(): Promise<void> {
  await Promise.all(Array.from({ length: N }, (_, i) => worker(i)));
  const matches = values.every((v, i) => v === ((i + 1) * (i + 2)) / 2);
  console.log("steps:", distances.length);
  console.log("barrier trips:", trips);
  console.log("prefix sums: [" + values.join(", ") + "]");
  console.log("matches a running total:", matches ? "True" : "False");
}

main();
Output
input: [1, 2, 3, 4, 5, 6, 7, 8]
steps: 3
barrier trips: 6
prefix sums: [1, 3, 6, 10, 15, 21, 28, 36]
matches a running total: True
  • Verdict: idiom. The tasks share one thread, so the barrier is a list of resolve functions that the last task to arrive calls. It shows the phases, not parallel work.
package main

import (
	"fmt"
	"strings"
	"sync"
)

// Barrier is a cyclic barrier for a fixed number of parties.
type Barrier struct {
	mu         sync.Mutex
	cond       *sync.Cond
	parties    int
	arrived    int
	generation int
	action     func()
}

func NewBarrier(parties int, action func()) *Barrier {
	b := &Barrier{parties: parties, action: action}
	b.cond = sync.NewCond(&b.mu)
	return b
}

func (b *Barrier) Wait() {
	b.mu.Lock()
	defer b.mu.Unlock()
	gen := b.generation
	b.arrived++
	if b.arrived == b.parties {
		b.action() // runs once per trip, before the goroutines are released
		b.arrived = 0
		b.generation++ // a new generation lets the barrier be used again
		b.cond.Broadcast()
		return
	}
	for gen == b.generation {
		b.cond.Wait()
	}
}

const N = 8

func show(v []int) string {
	parts := make([]string, len(v))
	for i, x := range v {
		parts[i] = fmt.Sprint(x)
	}
	return "[" + strings.Join(parts, ", ") + "]"
}

func main() {
	values := make([]int, N)
	for i := range values {
		values[i] = i + 1
	}
	distances := []int{1, 2, 4} // each step adds the value that is d places to the left
	fmt.Println("input:", show(values))
	trips := 0
	barrier := NewBarrier(N, func() { trips++ })

	var wg sync.WaitGroup
	for i := 0; i < N; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for _, d := range distances {
				// Phase 1: read a value that the last step wrote.
				add := 0
				if i >= d {
					add = values[i-d]
				}
				barrier.Wait() // nobody writes until every worker has read
				// Phase 2: write the new value.
				values[i] += add
				barrier.Wait() // nobody reads until every worker has written
			}
		}()
	}
	wg.Wait()

	matches := true
	for i, v := range values {
		matches = matches && v == (i+1)*(i+2)/2
	}
	fmt.Println("steps:", len(distances))
	fmt.Println("barrier trips:", trips)
	fmt.Println("prefix sums:", show(values))
	fmt.Println("matches a running total:", map[bool]string{true: "True", false: "False"}[matches])
}
Output
input: [1, 2, 3, 4, 5, 6, 7, 8]
steps: 3
barrier trips: 6
prefix sums: [1, 3, 6, 10, 15, 21, 28, 36]
matches a running total: True
  • Verdict: idiom. The standard library has no barrier, so the example builds a cyclic one from sync.Mutex, sync.Cond and a generation counter. sync.WaitGroup waits once and is not cyclic.
RustGitHub
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Barrier;
use std::thread;

const N: usize = 8;

fn main() {
    let values: Vec<AtomicI32> = (1..=N as i32).map(AtomicI32::new).collect();
    let distances = [1, 2, 4]; // each step adds the value that is d places to the left
    let show = |v: &[AtomicI32]| v.iter().map(|x| x.load(Ordering::SeqCst)).collect::<Vec<_>>();
    println!("input: {:?}", show(&values));
    let trips = AtomicI32::new(0);
    let barrier = Barrier::new(N);

    thread::scope(|s| {
        for i in 0..N {
            let (values, barrier, trips) = (&values, &barrier, &trips);
            s.spawn(move || {
                for d in distances {
                    // Phase 1: read a value that the last step wrote.
                    let add = if i >= d { values[i - d].load(Ordering::SeqCst) } else { 0 };
                    // Nobody writes until every worker has read. One thread is the leader of each trip.
                    if barrier.wait().is_leader() {
                        trips.fetch_add(1, Ordering::SeqCst);
                    }
                    // Phase 2: write the new value.
                    values[i].fetch_add(add, Ordering::SeqCst);
                    // Nobody reads until every worker has written.
                    if barrier.wait().is_leader() {
                        trips.fetch_add(1, Ordering::SeqCst);
                    }
                }
            });
        }
    });

    let result = show(&values);
    let matches = (0..N).all(|i| result[i] == ((i + 1) * (i + 2) / 2) as i32);
    println!("steps: {}", distances.len());
    println!("barrier trips: {}", trips.load(Ordering::SeqCst));
    println!("prefix sums: {:?}", result);
    println!("matches a running total: {}", if matches { "True" } else { "False" });
}
Output
input: [1, 2, 3, 4, 5, 6, 7, 8]
steps: 3
barrier trips: 6
prefix sums: [1, 3, 6, 10, 15, 21, 28, 36]
matches a running total: True
  • Verdict: stdlib. std::sync::Barrier; wait returns a result whose is_leader() is true for one thread per trip, and that thread counts the trip.

Consequences

Benefits:

  • The phases are clear in the code. Each phase can read the results of the last phase without a lock, because no thread writes while the others read.
  • The threads stay alive across the phases, so the program does not start new threads for each step.
  • One thread can do the work that comes between phases. The return value of Python's wait() is an integer in the range 0 to parties – 1, different for each thread, which can be used to select a thread to do some special housekeeping.2

Liabilities:

  • Every phase is as slow as its slowest thread, because all the other threads wait at the barrier for it.
  • The number of parties must be right. If one thread does not arrive, the others wait. Java's CyclicBarrier uses an all-or-none breakage model: if a thread leaves a barrier point because of interruption, failure, or timeout, all other threads waiting at that barrier point also leave abnormally.3
  • The fixed number of parties does not suit work whose size changes. Python's barrier is for use by a fixed number of threads that need to wait for each other.2

In this program, worker 3 fails before it reaches the barrier. The other three workers wait for a party that will not come:

This code runs but gives a wrong answer on purpose.

import threading

barrier = threading.Barrier(4, timeout=0.5)
lock = threading.Lock()
broken = 0


def worker(i):
    global broken
    try:
        if i == 3:
            raise ValueError("bad input")  # this worker fails before the barrier
        barrier.wait()
    except ValueError:
        print("worker 3 failed before the barrier")
        # Wrong: the worker leaves, and the barrier still waits for 4 parties.
    except threading.BrokenBarrierError:
        with lock:
            broken += 1


threads = [threading.Thread(target=worker, args=(i,)) for i in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("workers that waited until the timeout broke the barrier:", broken)
Output
worker 3 failed before the barrier
workers that waited until the timeout broke the barrier: 3

The three workers end only because the barrier has a timeout. A worker that cannot continue should call abort(), which puts the barrier into a broken state so that waiting and future calls to wait() fail with BrokenBarrierError.2 Python's documentation describes this as a way to avoid deadlocking the application.2

When not to use it

Do not use a barrier when the threads do not depend on each other's results between steps. A thread pool or one fork-join step is simpler. Do not use a barrier to wait for one result. A future does that. Do not use a barrier when the number of threads changes during the computation, unless the barrier supports registration, as the Phaser below does.

  • Leader of a phase. One thread does the work between phases. Rust's Barrier::wait gives a single, arbitrary thread a result that returns true from is_leader(), and all other threads get false.5 Python gives each thread an index:
import threading

barrier = threading.Barrier(4, timeout=5)
lock = threading.Lock()
chosen = [0, 0, 0]  # how many threads got index 0 in each phase


def worker():
    for phase in range(3):
        i = barrier.wait()  # an index from 0 to 3, different for each thread
        if i == 0:  # one thread per phase does the housekeeping
            with lock:
                chosen[phase] += 1


threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("phases:", len(chosen))
print("threads that got index 0 in each phase:", chosen)
Output
phases: 3
threads that got index 0 in each phase: [1, 1, 1]
  • Latch. The term latch is sometimes used for a barrier that starts in the raised state and cannot be re-raised once it is in the lowered state.1 A count-down latch is a latch that is automatically lowered once a predetermined number of threads or processes have arrived.1 A latch is used once. A cyclic barrier is used for many phases.
  • Phaser. A Java Phaser is a reusable synchronization barrier, similar to CyclicBarrier and CountDownLatch but supporting more flexible usage.6 Unlike other barriers, the number of parties registered to synchronize on a phaser may vary over time.6 Phasers may be tiered, constructed in tree structures, to reduce contention.6
  • Implicit barriers. Many collective routines and directive-based parallel languages impose implicit barriers, and in message passing, any global communication, such as reduction or scatter, may imply a barrier.1

Each barrier wait is a form of guarded suspension: the guard is that all parties have arrived. The Go example builds a barrier from a monitor object with a mutex, a condition variable and a generation counter.

Known uses

  • Python threading.Barrier, with an optional action and timeout.2
  • Java CyclicBarrier and Phaser.36
  • Rust std::sync::Barrier.5
  • The barrier synchronization at the end of each superstep of the bulk synchronous parallel model, which Leslie Valiant developed at Harvard University during the 1980s.4

References

  1. Barrier (computer science), Wikipedia, lead
  2. threading, Thread-based parallelism, Python documentation, Barrier Objects
  3. Java SE 21 API, java.util.concurrent.CyclicBarrier, the class description
  4. Bulk synchronous parallel, Wikipedia, The model; History
  5. The Rust Standard Library, std::sync::Barrier, the type description; wait
  6. Java SE 21 API, java.util.concurrent.Phaser, the class description

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)
WritingW3 standard
  • a history with a source