Concurrency in C++: Threads, Mutexes, Atomics, Futures and C++20 Synchronization

Threads, mutexes, atomics, condition variables and futures in modern C++, with tested programs and the data races, deadlocks and hangs to avoid.

Three thread lanes meeting at a locked box, one passing through while the other two wait their turn

Since C++11, the standard library has had everything a program needs to run work on several threads: std::thread to start them, mutexes and atomics to share data safely, condition variables to make threads wait for each other and futures to hand results back. C++20 added std::jthread, latches, barriers and semaphores. What the library cannot do is make shared data safe on its own, and the bugs that follow (data races, deadlocks, lost wake-ups) are among the hardest in C++ to find.

This guide covers each tool with a short, complete program, and shows how each common bug looks when it happens. Every program was compiled and tested with GCC and Clang (C++17 and C++20, warnings as errors, under AddressSanitizer and ThreadSanitizer) and with MSVC on Windows 11, and each output is captured verbatim.

The Short Answer

How do you run code concurrently in C++? Start a std::thread (or C++20 std::jthread) with a function, and join() it before it goes out of scope. For a single result, std::async returns a std::future you can wait on.

How do threads share data safely? Protect shared data with a std::mutex (through std::lock_guard or std::scoped_lock), or make it a std::atomic if it is a single counter or flag. Two threads touching the same data without either is a data race, which is undefined behavior.

How do threads wait for each other? With std::condition_variable for “wait until something changes”, futures for “wait for a result”, and the C++20 std::latch, std::barrier and std::counting_semaphore for common coordination patterns.

What Is Concurrency in C++?

Concurrency means a program has several tasks in progress at the same time, each on its own thread of execution. On a multi-core processor the threads can run in parallel; on one core they take turns. In C++, all threads of a process share its memory, so any data that more than one thread reads and writes needs synchronization.

Concurrency and parallelism are related but different. Concurrency is about structure: a server that handles many clients, a program that keeps its UI responsive while it works. Parallelism is about speed: splitting one computation across cores. The same tools serve both.

The standard library’s concurrency toolkit, by header:

HeaderMain typesUse it for
<thread>std::thread, std::jthread (C++20), std::this_threadStarting and joining threads
<mutex>std::mutex, std::lock_guard, std::unique_lock, std::scoped_lockProtecting shared data
<atomic>std::atomic<T>Lock-free counters, flags and pointers
<condition_variable>std::condition_variableWaiting until a condition becomes true
<future>std::async, std::future, std::promise, std::packaged_taskGetting results and exceptions back from a thread
<latch>, <barrier>, <semaphore> (C++20)std::latch, std::barrier, std::counting_semaphoreCommon coordination patterns
<stop_token> (C++20)std::stop_token, std::stop_sourceAsking a thread to stop
How a data race loses an increment No lock: ++count twice Thread A Thread B read count: 41 read count: 41 add 1: 42 add 1: 42 write 42 write 42 count is 42, not 43: one increment lost With a mutex Thread A Thread B lock, read 41 lock: waits write 42, unlock lock, read 42 write 43, unlock count is 43: no step overlaps
Figure 1: ++count is three steps. Without a lock two threads can interleave them and lose an update; a mutex makes each increment run as a whole.

Starting and Joining Threads

A std::thread starts running its function as soon as it is constructed. Before the std::thread object is destroyed, you must either join() it (wait for it to finish) or detach() it (let it run on its own). If you do neither, the destructor calls std::terminate and the program ends.

// threads_basics.cpp - starting threads, passing arguments, joining, and
// std::jthread, which joins by itself.
#include <functional>
#include <iostream>
#include <string>
#include <thread>
#include <vector>

void fill(std::vector<int>& out, int from, int count)
{
    for (int i = 0; i < count; ++i)
        out.push_back(from + i);
}

int main()
{
    // 1. A thread runs a function; join() waits for it to finish.
    std::vector<int> numbers;
    std::thread worker(fill, std::ref(numbers), 10, 5);   // std::ref: pass by reference
    worker.join();
    std::cout << "worker filled " << numbers.size() << " numbers, first " << numbers.front() << '\n';

    // 2. Arguments are copied into the thread unless wrapped in std::ref.
    std::string label = "unchanged";
    std::thread copier([](std::string s) { s += " (changed in thread)"; }, label);
    copier.join();
    std::cout << "label after thread: " << label << '\n';

    // 3. Each thread writes only its own slot, so no locking is needed.
    std::vector<long> partial(4);
    std::vector<std::thread> pool;
    for (int t = 0; t < 4; ++t)
        pool.emplace_back([&partial, t] {
            for (long i = t * 250; i < (t + 1) * 250; ++i)
                partial[static_cast<std::size_t>(t)] += i;
        });
    for (std::thread& th : pool)
        th.join();
    long total = 0;
    for (long p : partial)
        total += p;
    std::cout << "sum of 0..999 from 4 threads: " << total << '\n';

    // 4. A std::thread that is still joinable when destroyed calls std::terminate.
    //    std::jthread (C++20) joins in its destructor instead. See cpp20_sync.cpp.
    std::cout << "hardware threads reported: " << (std::thread::hardware_concurrency() > 0 ? "at least 1" : "unknown") << '\n';
}

Output:

worker filled 5 numbers, first 10
label after thread: unchanged
sum of 0..999 from 4 threads: 499500
hardware threads reported: at least 1

Three rules from this program:

  • Arguments are copied into the thread. label is unchanged because the thread got its own copy. To pass a reference, wrap the argument in std::ref, as the first thread does with numbers.
  • Threads that write different objects need no locking. Each of the four threads in step 3 writes only partial[t], so there is no shared write. Collecting results this way and combining them after join() is the simplest correct pattern.
  • hardware_concurrency() is a hint. It may return 0 when the number is unknown, so do not divide by it.

Prefer join() to detach(). A detached thread may still be running when main returns and global objects are destroyed under it.

Data Races: What Goes Wrong Without Synchronization

counter.cpp has four threads add 1 to the same counter 100,000 times each, in three ways:

// counter.cpp - four threads increment one counter 100,000 times each.
//   counter mutex    a std::mutex protects the counter       (always 400000)
//   counter atomic   the counter is a std::atomic<long>       (always 400000)
//   counter racy     no protection: a data race, undefined behavior.
//                    Build with -fsanitize=thread to see it reported.
#include <atomic>
#include <iostream>
#include <mutex>
#include <string_view>
#include <thread>
#include <vector>

constexpr int kThreads = 4;
constexpr int kIncrements = 100'000;

template <class Increment>
void run(Increment increment)
{
    std::vector<std::thread> threads;
    for (int t = 0; t < kThreads; ++t)
        threads.emplace_back([&] {
            for (int i = 0; i < kIncrements; ++i)
                increment();
        });
    for (std::thread& t : threads)
        t.join();
}

int main(int argc, char** argv)
{
    const std::string_view mode = argc > 1 ? argv[1] : "mutex";

    if (mode == "mutex") {
        long count = 0;
        std::mutex m;
        run([&] {
            std::lock_guard<std::mutex> lock(m);   // unlocked when lock goes out of scope
            ++count;
        });
        std::cout << "mutex:  " << count << '\n';
    } else if (mode == "atomic") {
        std::atomic<long> count{0};
        run([&] { count.fetch_add(1, std::memory_order_relaxed); });
        std::cout << "atomic: " << count.load() << '\n';
    } else if (mode == "racy") {
        long count = 0;
        run([&] { ++count; });                     // two threads may read the same old value
        std::cout << "racy:   " << count << " (expected 400000)\n";
    } else {
        std::cout << "usage: counter mutex|atomic|racy\n";
        return 2;
    }
}

The mutex and atomic versions always print 400,000:

mutex:  400000
atomic: 400000

The racy version is the instructive one. ++count is three steps (read, add, write), and two threads can read the same old value, both add 1 and both write back the same result, so one increment is lost. Built with GCC at -O0, five runs printed:

racy:   315899 (expected 400000)
racy:   334104 (expected 400000)
racy:   312329 (expected 400000)
racy:   332210 (expected 400000)
racy:   329500 (expected 400000)

Clang at -O0 lost increments the same way (297,661 and 323,923 in two runs). Built at -O2, the same code printed 400,000 in every run with both compilers (five with GCC, three with Clang), most likely because the optimizer turned each thread’s loop into a single addition. That is not a fix. The race is still there; it just did not show up on this compiler, at this optimization level, on this machine. MSVC’s optimized Release build, on the other hand, lost about 40% of the increments: 223,160, 233,193 and 235,127 in three runs. The same source is “correct” with one compiler and badly wrong with another.

This is why data races are dangerous: the C++ standard calls them undefined behavior, and testing alone cannot prove their absence. ThreadSanitizer can. Building with -fsanitize=thread (GCC and Clang) finds the race on the first run, at any optimization level:

WARNING: ThreadSanitizer: data race (pid=300)
    #0 operator() src/counter.cpp:47
SUMMARY: ThreadSanitizer: data race src/counter.cpp:47 in operator()

Line 47 is the ++count in the racy lambda. The mutex and atomic versions run clean under ThreadSanitizer, and so does every other program in this guide. Run your tests under it regularly; it is the single most useful tool for concurrent C++.

Mutexes, Locks and Atomics

A std::mutex lets one thread at a time into a critical section. Never call lock() and unlock() yourself: if the code in between throws or returns early, the mutex stays locked forever. Use a lock object that unlocks in its destructor, the same RAII idea described in C++ memory management:

LockLocksUse it when
std::lock_guard<std::mutex>One mutex, for the whole scopeThe default for a simple critical section
std::scoped_lock (C++17)One or more mutexes at once, deadlock-freeYou need two or more mutexes
std::unique_lock<std::mutex>One mutex; can unlock early, relock, be movedWith condition variables, or to unlock before slow work

A std::atomic<T> makes single operations on one variable indivisible without a lock. count.fetch_add(1) is safe from any number of threads. Atomics are the right tool for counters, flags and “has this happened yet” states; anything that spans two variables (a balance and a transaction log, say) still needs a mutex, because two separate atomic operations are not atomic together.

The std::memory_order_relaxed argument in counter.cpp says the increment does not need to order any other memory operations, which is true for a pure counter that is read after join(). The default, std::memory_order_seq_cst, is always correct and the right choice unless you have measured a reason to weaken it.

Avoiding Deadlock with std::scoped_lock

A deadlock happens when two threads each hold one mutex and wait for the other’s. The classic case is a transfer between two accounts, run in opposite directions:

// transfers.cpp - moving money between two accounts from two threads in
// opposite directions. Locking both mutexes with std::scoped_lock avoids the
// deadlock that locking them one at a time, in different orders, can cause.
#include <iostream>
#include <mutex>
#include <thread>

struct Account {
    std::mutex m;
    long balance = 0;
};

void transfer(Account& from, Account& to, long amount)
{
    std::scoped_lock lock(from.m, to.m);   // locks both, deadlock-free, in any order
    from.balance -= amount;
    to.balance += amount;
}

int main()
{
    Account a, b;
    a.balance = 1000;
    b.balance = 1000;

    std::thread t1([&] { for (int i = 0; i < 100'000; ++i) transfer(a, b, 1); });
    std::thread t2([&] { for (int i = 0; i < 100'000; ++i) transfer(b, a, 1); });
    t1.join();
    t2.join();

    std::cout << "a = " << a.balance << ", b = " << b.balance
              << ", total = " << a.balance + b.balance << '\n';
}

Output:

a = 1000, b = 1000, total = 2000

std::scoped_lock lock(from.m, to.m) locks both mutexes using a deadlock-avoidance algorithm, so the order of the arguments does not matter. Replacing it with two std::lock_guards, from.m first and to.m second, deadlocked in each of three test runs: thread 1 locked a and waited for b while thread 2 locked b and waited for a, and the program had to be killed after 10 seconds. The test suite’s deliberate-mistake check makes exactly that change and confirms the test catches the hang.

The general rule: if code ever holds two locks, either take them together with std::scoped_lock or always take them in one global order.

Condition Variables: A Thread-Safe Bounded Queue

A producer-consumer queue is the workhorse of concurrent programs: some threads put work in, others take it out, and a capacity limit stops producers from running far ahead. It needs a mutex for the data and two condition variables, one for “not full” and one for “not empty”:

// bounded_queue.h - a thread-safe queue with a capacity limit.
// push() waits while the queue is full; pop() waits while it is empty.
// close() wakes everyone: pop() then drains what is left and returns
// std::nullopt, and push() returns false.
#pragma once

#include <condition_variable>
#include <cstddef>
#include <deque>
#include <mutex>
#include <optional>
#include <utility>

template <class T>
class BoundedQueue {
public:
    explicit BoundedQueue(std::size_t capacity) : capacity_(capacity) {}

    bool push(T value)
    {
        std::unique_lock<std::mutex> lock(mutex_);
        // wait() unlocks, sleeps and relocks; the predicate guards against
        // spurious wakeups and against conditions that changed before we woke.
        not_full_.wait(lock, [this] { return items_.size() < capacity_ || closed_; });
        if (closed_)
            return false;
        items_.push_back(std::move(value));
        lock.unlock();                 // notify after unlocking: the woken thread can run at once
        not_empty_.notify_one();
        return true;
    }

    std::optional<T> pop()
    {
        std::unique_lock<std::mutex> lock(mutex_);
        not_empty_.wait(lock, [this] { return !items_.empty() || closed_; });
        if (items_.empty())
            return std::nullopt;       // closed and drained
        T value = std::move(items_.front());
        items_.pop_front();
        lock.unlock();
        not_full_.notify_one();
        return value;
    }

    void close()
    {
        {
            std::lock_guard<std::mutex> lock(mutex_);
            closed_ = true;
        }
        not_empty_.notify_all();
        not_full_.notify_all();
    }

private:
    std::mutex mutex_;
    std::condition_variable not_full_;
    std::condition_variable not_empty_;
    std::deque<T> items_;
    const std::size_t capacity_;
    bool closed_ = false;
};

Three details make it correct:

  • Always wait with a predicate. wait(lock, [] { return ...; }) re-checks the condition after every wake-up. Without it, a spurious wakeup (which the standard allows) or a condition that changed before the thread got the lock would let pop() read from an empty queue.
  • close() must wake everyone. Consumers blocked in pop() sleep until notified. If close() set the flag without notify_all(), they would sleep forever. The deliberate-mistake check removes that call, and the test hangs until its timeout.
  • Notify after unlocking. Calling notify_one() after lock.unlock() lets the woken thread take the mutex at once instead of waking up only to block on it.

Two producers send +1 to +10,000 and -1 to -10,000; three consumers add up what they receive:

// producer_consumer.cpp - two producers and three consumers share a
// BoundedQueue with room for 8 items.
#include "bounded_queue.h"

#include <iostream>
#include <thread>
#include <vector>

int main()
{
    BoundedQueue<int> queue(8);
    constexpr int kPerProducer = 10'000;

    std::vector<std::thread> producers;
    for (int p = 0; p < 2; ++p)
        producers.emplace_back([&queue, p] {
            for (int i = 1; i <= kPerProducer; ++i)
                queue.push(p == 0 ? i : -i);       // producer 1 sends negatives
        });

    // Each consumer adds up what it receives in its own variables.
    std::vector<long> sums(3), counts(3);
    std::vector<std::thread> consumers;
    for (std::size_t c = 0; c < 3; ++c)
        consumers.emplace_back([&, c] {
            while (auto item = queue.pop()) {
                sums[c] += *item;
                ++counts[c];
            }
        });

    for (std::thread& t : producers)
        t.join();
    queue.close();                                 // no more items: let consumers finish
    for (std::thread& t : consumers)
        t.join();

    long total = 0, received = 0;
    for (std::size_t c = 0; c < 3; ++c) {
        total += sums[c];
        received += counts[c];
    }
    std::cout << "items received: " << received << '\n'
              << "sum (should be 0): " << total << '\n'
              << "push after close accepted: " << std::boolalpha << queue.push(1) << '\n';
}

Output:

items received: 20000
sum (should be 0): 0
push after close accepted: false

All 20,000 items arrive, the sum is exactly zero and no item is lost or duplicated, whichever consumer happened to take each one.

Futures: Results and Exceptions from Other Threads

When a thread exists to compute one value, a future is simpler than a shared variable and a mutex:

// futures.cpp - getting results and exceptions back from other threads:
// std::async, std::promise and std::packaged_task.
#include <cstddef>
#include <future>
#include <iostream>
#include <numeric>
#include <stdexcept>
#include <thread>
#include <vector>

long sum_range(const std::vector<int>& v, std::size_t from, std::size_t to)
{
    return std::accumulate(v.begin() + static_cast<std::ptrdiff_t>(from), v.begin() + static_cast<std::ptrdiff_t>(to), 0L);
}

int parse_positive(int value)
{
    if (value <= 0)
        throw std::invalid_argument("value must be positive");
    return value;
}

int main()
{
    std::vector<int> data(1000);
    std::iota(data.begin(), data.end(), 1);        // 1..1000

    // std::async: run a function and get its result through a future.
    // std::launch::async forces a new thread instead of possibly deferring.
    auto first_half = std::async(std::launch::async, sum_range, std::cref(data), std::size_t{0}, std::size_t{500});
    const long second_half = sum_range(data, 500, 1000);
    std::cout << "async sum: " << first_half.get() + second_half << '\n';

    // An exception thrown in the task is stored and rethrown by get().
    auto bad = std::async(std::launch::async, parse_positive, -5);
    try {
        bad.get();
    } catch (const std::invalid_argument& e) {
        std::cout << "exception from the other thread: " << e.what() << '\n';
    }

    // std::promise: a thread sets the value whenever it is ready.
    std::promise<std::string> promise;
    std::future<std::string> greeting = promise.get_future();
    std::thread sender([p = std::move(promise)]() mutable { p.set_value("hello from a promise"); });
    std::cout << greeting.get() << '\n';
    sender.join();

    // std::packaged_task: wrap a callable now, run it later on any thread.
    std::packaged_task<int(int)> task(parse_positive);
    std::future<int> result = task.get_future();
    std::thread runner(std::move(task), 42);
    std::cout << "packaged_task result: " << result.get() << '\n';
    runner.join();
}

Output:

async sum: 500500
exception from the other thread: value must be positive
hello from a promise
packaged_task result: 42
  • std::async runs a function and returns a std::future for its result. Pass std::launch::async to guarantee a new thread; without it, the implementation may defer the call until get(), running it on the calling thread.
  • Exceptions travel through the future. parse_positive(-5) throws on the other thread; get() rethrows it on this one. This is the main advantage over a raw std::thread, where an uncaught exception terminates the program. The exception handling guide covers what to do with it.
  • std::promise separates producing a value from the function call: any thread can set_value() (or set_exception()) whenever the result is ready.
  • std::packaged_task wraps a callable so you can run it later, on any thread, and still get a future.

One trap: the destructor of a future returned by std::async waits for the task to finish. Calling std::async without keeping the result therefore runs the task synchronously, and two such calls in a row run one after the other.

C++20: jthread, Stop Tokens, Latches, Barriers and Semaphores

C++20 added five tools that replace common hand-written patterns:

// cpp20_sync.cpp - the C++20 additions: std::jthread with a stop token,
// std::latch, std::barrier and std::counting_semaphore.
#include <algorithm>
#include <atomic>
#include <barrier>
#include <chrono>
#include <iostream>
#include <latch>
#include <semaphore>
#include <thread>
#include <vector>

int main()
{
    // 1. jthread: request_stop() asks the thread to finish; the destructor joins.
    std::atomic<int> ticks{0};
    {
        std::jthread ticker([&ticks](std::stop_token stop) {
            while (!stop.stop_requested()) {
                ++ticks;
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
        });
        while (ticks < 5)
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        ticker.request_stop();
    }   // joined here, no explicit join() needed
    std::cout << "jthread stopped after at least 5 ticks: " << std::boolalpha << (ticks >= 5) << '\n';

    // 2. latch: a one-shot countdown. main waits until all 3 workers are ready.
    std::latch ready(3);
    std::vector<std::jthread> workers;
    for (int i = 0; i < 3; ++i)
        workers.emplace_back([&ready] { ready.count_down(); });
    ready.wait();
    std::cout << "latch: all 3 workers ready\n";
    workers.clear();   // jthreads join as they are destroyed

    // 3. barrier: threads meet at the end of each phase; the completion
    //    function runs once per phase, before anyone continues.
    int phases_done = 0;
    std::barrier sync(3, [&phases_done]() noexcept { ++phases_done; });
    for (int i = 0; i < 3; ++i)
        workers.emplace_back([&sync] {
            for (int phase = 0; phase < 4; ++phase)
                sync.arrive_and_wait();
        });
    workers.clear();
    std::cout << "barrier: " << phases_done << " phases completed\n";

    // 4. counting_semaphore: at most 2 of the 6 threads inside at once.
    std::counting_semaphore<2> slots(2);
    std::atomic<int> inside{0}, most{0};
    for (int i = 0; i < 6; ++i)
        workers.emplace_back([&] {
            slots.acquire();
            const int now = ++inside;
            int seen = most.load();
            while (now > seen && !most.compare_exchange_weak(seen, now)) {
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(20));
            --inside;
            slots.release();
        });
    workers.clear();
    std::cout << "semaphore: at most " << most.load() << " threads inside at once\n";
}

Output:

jthread stopped after at least 5 ticks: true
latch: all 3 workers ready
barrier: 4 phases completed
semaphore: at most 2 threads inside at once
ToolUse instead ofBehavior
std::jthreadstd::thread plus a manual join()Joins in its destructor, and passes a std::stop_token to its function
std::stop_tokenA hand-rolled std::atomic<bool> “please stop” flagrequest_stop() sets it; the thread checks stop_requested()
std::latchA counter plus a condition variableCounts down once; wait() returns when it reaches zero
std::barrierRepeated latchesReusable: threads meet at the end of each phase, and an optional function runs once per phase
std::counting_semaphoreA mutex-protected counter of free slotsacquire() takes a slot, release() returns it; limits how many threads do something at once

std::jthread is the one to adopt first: it removes the “forgot to join” crash, and stop tokens make cancellation explicit instead of an ad hoc flag. In the program above, six threads compete for a two-slot semaphore and at most two are ever inside, as the output confirms.

Common Mistakes in Concurrent C++

  • Sharing a variable without a mutex or an atomic. Even ++count is a data race. Run the tests under ThreadSanitizer.
  • Trusting a passing test. The racy counter printed the right answer every time with GCC and Clang at -O2, and lost 40% of its updates with MSVC. A race can stay hidden for a long time.
  • Calling lock() and unlock() by hand. An exception between them leaves the mutex locked. Use std::lock_guard or std::scoped_lock.
  • Taking two locks in different orders. Use std::scoped_lock for both, or a fixed order.
  • Waiting on a condition variable without a predicate. Spurious wakeups and missed notifications break it.
  • Forgetting to notify waiters on shutdown. Threads blocked in wait() never see the closed flag.
  • Destroying a joinable std::thread. The program terminates. Join it, or use std::jthread.
  • Holding a lock while doing slow work (I/O, allocation, calling user code). Copy what you need, unlock, then work.
  • Assuming std::async without std::launch::async runs in parallel. It may be deferred.
  • Capturing local variables by reference in a detached thread. The function returns, the locals die and the thread reads freed memory.

Key Takeaways

  • Start threads with std::thread or std::jthread; join every std::thread before it is destroyed.
  • Any data that one thread writes and another reads needs a mutex or an atomic. Without one it is a data race and undefined behavior.
  • Use RAII locks: std::lock_guard for one mutex, std::scoped_lock for several.
  • Wait on condition variables with a predicate, and notify waiters when you shut down.
  • Use futures to get results and exceptions back from other threads.
  • In C++20, prefer std::jthread with stop tokens, and use latches, barriers and semaphores instead of hand-written equivalents.
  • Test concurrent code under ThreadSanitizer: it finds races that ordinary tests miss.

Conclusion

Concurrent C++ comes down to two questions for every piece of data: which threads touch it, and what stops them from touching it at the same time. The standard library answers the second with a small set of tools: mutexes and atomics for sharing, condition variables and futures for waiting and the C++20 primitives for the common patterns built on top of them. The bugs come from the first question, and the tools that find them, ThreadSanitizer above all, are as much a part of writing concurrent code as the threads themselves.

For a real program built on these pieces, the named pipes article uses one std::thread per client, and smart pointers in C++ explains which shared_ptr operations are thread-safe. More C++ topics are in the C++ section.

Source Code and Tests

concurrency workflow status

All programs on this page are in the basics/concurrency directory of the MYCPLUS C++ examples repository.

Build and test:

cmake -S . -B build
cmake --build build --config Release
ctest --test-dir build -C Release --output-on-failure

What the build checks.

  • Compilers: GCC and Clang under C++17 and C++20 with -Wall -Wextra -pedantic -Werror, and MSVC with /W4 /WX /permissive-. cpp20_sync.cpp is always built as C++20.
  • Output: each program prints exactly the output shown on this page. Every test has a timeout, because a concurrency bug often shows up as a hang rather than a wrong answer.
  • Sanitizers: on Linux, every test also runs under AddressSanitizer with UndefinedBehaviorSanitizer and under ThreadSanitizer, and ThreadSanitizer must report the race in counter racy.
  • Repetition: the workflow runs the suite five times in a row, to catch tests that pass only by luck.

What I Verified

Everything in the Ubuntu column was run for this article on Ubuntu 24.04 (x86-64, 2 cores, GCC 13.3, Clang 18.1, CMake 3.28). The Windows column comes from run_all.ps1 in the repository, run on Windows 11 (build 26300) with MSVC.

CheckUbuntu 24.04Windows 11
Build with warnings as errorsGCC and Clang, C++17 and C++20: passedMSVC /W4 /WX /permissive-, C++17 and C++20: passed
CTest: 7 output comparisons7 of 7 in all four configurations7 of 7 in C++17 and in C++20
Every test 20 times in a row20 of 20 (GCC, C++17)20 of 20 (MSVC, C++17)
AddressSanitizer and UndefinedBehaviorSanitizer, every test7 of 7, cleanNot applicable
ThreadSanitizer, every test7 of 7, clean; the racy counter reportedNot applicable
Valgrind memcheck, every programNo errors, no leaksNot applicable
Deliberate mistakes that a test must catchAll 4 caughtAll 3 caught (the removed-lock mistake needs ThreadSanitizer)

Not covered: parallel algorithms (std::execution::par), coroutines, lock-free data structures beyond a single atomic and memory orders other than relaxed and sequentially consistent.

Scroll to Top