C++20 Latches and Barriers: Coordinating Worker Threads

Rendered terminal transcript of actual C++20 latch and barrier test results.

Open Source C++ Programming | Super-fundamental curriculum | 45–60 minutes

Parallel computation frequently divides a task among workers, but the workers must eventually coordinate. A network inventory program might wait until several independent discovery operations finish. An iterative numerical program might need every worker to finish calculating a partial result before beginning another iteration. C++20 introduces two standard-library coordination primitives for such problems: std::latch and std::barrier.

Prerequisites

Review atomic wait and notify, jthread and cooperative shutdown, futures and launch policies and packaged tasks. A compiler and standard library supporting the C++20 latch and barrier headers are required.

Learning objectives

  • Distinguish one-time coordination from repeated phase synchronization.
  • Build and execute a latch program and a barrier program.
  • Explain memory visibility and why a synchronization point does not protect every shared operation.
  • Recognize incorrect participant counts, premature destruction and deadlock risks.
CppCon 2022, Anthony Williams: An Introduction to Multithreading in C++20. Explains modern standard-library concurrency and coordination tools. Watch directly on YouTube.

A latch coordinates one milestone

A latch contains a counter initialized at construction. count_down() subtracts a contribution without waiting, wait() blocks until the counter reaches zero, and arrive_and_wait() combines both operations. Once zero is reached, the object cannot be reset for another phase. try_wait() provides a nonblocking readiness check; a false result may be spurious. See the C++ working draft latch specification and cppreference API reference.

Create latch.cpp. Three workers write to separate array elements, then signal completion. The main thread waits for all three contributions before reading the results.

#include <array>
#include <cassert>
#include <iostream>
#include <latch>
#include <thread>

int main() {
    std::array<int, 3> results{};
    std::latch ready(3);
    std::array<std::jthread, 3> workers;
    for (int i = 0; i < 3; ++i) {
        workers[i] = std::jthread([&, i] {
            results[i] = (i + 1) * 10;
            ready.count_down();
        });
    }
    ready.wait();
    int total = results[0] + results[1] + results[2];
    assert(total == 60);
    std::cout << “Latch total: ” << total << ‘\n’;
}

Compile with g++ -std=c++20 -O2 -Wall -Wextra -Werror -pthread latch.cpp -o latch and run ./latch. Observed output: Latch total: 60. Each worker owns a separate array element. The latch establishes the synchronization needed to read those completed writes after wait returns. The worker objects remain alive and are joined during destruction; waiting on a latch is not itself a thread join.

A barrier coordinates repeated phases

A barrier represents a sequence of synchronization phases. Each arrival reduces the remaining count for the current phase. After the required contributions arrive, a completion step runs before waiting workers proceed. The count is then reset for the next phase, accounting for any participants that have dropped out. The completion callback must satisfy the nonthrowing invocation requirement. Read the working draft barrier specification and barrier reference.

CppCon 2020, Arthur O’Dwyer: Back to Basics: Concurrency. Compares locks, condition variables and C++20 synchronization primitives. Watch directly on YouTube.

Create barrier.cpp. Three workers compute independent partial values for four rounds. At each rendezvous, the completion callback sums their values into a separate result array. Every worker waits until the callback finishes before writing its next contribution.

#include <array>
#include <barrier>
#include <cassert>
#include <iostream>
#include <thread>

int main() {
    std::array<int, 3> partial{};
    std::array<int, 4> sums{};
    int phase = 0;
    std::barrier gate(3, [&]() noexcept {
        sums[phase++] = partial[0] + partial[1] + partial[2];
    });
    {
        std::array<std::jthread, 3> workers;
        for (int i = 0; i < 3; ++i) {
            workers[i] = std::jthread([&, i] {
                for (int round = 1; round <= 4; ++round) {
                    partial[i] = (i + 1) * round;
                    gate.arrive_and_wait();
                }
            });
        }
    }
    assert(phase == 4);
    assert((sums == std::array<int, 4>{6, 12, 18, 24}));
    for (int value : sums) std::cout << value << ‘ ‘;
    std::cout << ‘\n’;
}

Compile with g++ -std=c++20 -O2 -Wall -Wextra -Werror -pthread barrier.cpp -o barrier and run ./barrier. Observed output: 6 12 18 24. The callback runs once per completed phase in the example, and the completion step orders the next phase after the reduction. The enclosing scope joins all workers before the main thread examines sums. The program does not depend on which worker executes the callback.

Choosing the coordination primitive

Use a latch for a one-time readiness milestone, such as waiting for independent configuration loaders. Use a barrier when a known set of participants must repeatedly rendezvous. A mutex instead protects shared mutable state from conflicting access. A semaphore controls access to a finite number of permits. A future conveys a result or exception from an asynchronous operation. Atomic wait is suitable when progress depends on observing a change to an atomic value. Neither a latch nor a barrier automatically makes arbitrary concurrent writes safe.

Common failures and professional practice

  • Match the expected count to the contributions that can actually arrive. An absent contribution can block progress indefinitely.
  • Never decrement a latch below zero, reset a latch, or destroy a synchronization object while another thread can access it.
  • A worker that must leave a repeated barrier protocol can use arrive_and_drop() under a correctly designed departure plan. Merely returning early or requesting cancellation does not release other waiting participants.
  • Do not hold a mutex while waiting at a synchronization point if another participant needs that mutex to arrive.
  • Plan failure and thread-creation handling before deploying fixed-count synchronization. These examples assume successful worker creation and do not implement production cancellation or recovery.
  • Keep phase completion work brief and nonthrowing. Avoid accidentally allowing the next phase to overwrite data still being read by another worker.

Verification and exercises

Both examples were compiled using GCC 14.2.0 with C++20, optimization and warnings treated as errors. A harness executed each binary 100 times with a two-second timeout and checked its expected output. All 200 executions passed. Assertions also checked the totals and phase count. The experiment demonstrates repeatability in the tested environment, not proof of correctness on every architecture or a measured performance advantage.

  • A latch begins at 5 and receives contributions of 2 and 1. What remains? Answer: 2.
  • Three workers rendezvous for four rounds. How many completed phases occur? Answer: 4, with 12 individual arrivals.
  • Why is a latch unsuitable for repeated phases? Answer: its counter cannot be reset.
  • Why must a barrier completion callback finish before the workers overwrite their partial results? Answer: the reduction must read the contributions for the current phase; phase synchronization orders subsequent writes.
  • What happens if one worker exits without satisfying the expected arrival protocol? Answer: remaining workers may wait indefinitely.

Glossary

Latch: single-use countdown coordination. Barrier: repeatable phase synchronization. Completion step: work associated with a completed barrier phase. Data race: conflicting unsynchronized accesses to a memory location, at least one of which modifies it, subject to the language’s atomic-access rules. Deadlock: a state in which progress is prevented by unresolved dependencies.

Editor’s Note: The cover is a rendered transcript of actual local lab results. The code examples were executed under the environment described above. The instructional talks are credited to their original presenters and conference; independent playback and mobile rendering have not been established.

We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiative, please scan the QR code below.

Optional 5,000-satoshi donation QR
Optional 5,000-satoshi contribution. Independently confirm the wallet address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb and payment amount before sending.

BitcoinVersus.tech is not a financial advisor. This media platform reports on financial subjects purely for informational purposes.

Leave a Reply