Concurrency and Multithreading

Article · 3:00

Running work on more than one core, the data race that is waiting if you do not synchronise, and the futures that are usually a better answer.

A thread is a separate flow of execution inside your process, sharing the same memory. std::thread t{function, args...} starts one immediately. Before the thread object is destroyed you must either join() it - wait for it to finish - or detach() it; neither, and the program calls std::terminate. C++20's std::jthread joins automatically in its destructor and can be cooperatively cancelled with a stop token, which removes an entire category of bug: prefer it.

The reason concurrency is hard is the data race. Two threads touching the same memory, at least one of them writing, with no synchronisation, is undefined behaviour - not "a wrong number sometimes", undefined. ++count from two threads is three operations (read, add, write) and they interleave, so increments are simply lost. The result is not deterministic, which is why a race can pass a thousand test runs and fail in production.

A mutex makes a region mutually exclusive: one thread holds it at a time. Never lock and unlock by hand, because any return or exception in between leaks the lock and deadlocks the program. Use std::lock_guard - RAII again - which locks on construction and unlocks on destruction, exception or not. std::unique_lock is the version you need when you must unlock early or hand the lock to a condition variable. When two mutexes must be held, lock them together with std::scoped_lock, which avoids the deadlock that two threads taking them in opposite orders would otherwise produce.

Atomics are the cheaper answer for a single variable. std::atomic<int> makes ++ one indivisible operation, with no mutex and usually a single processor instruction. For a counter or a flag it is the right tool; it does not extend to keeping two variables consistent with each other.

Most of the time, don't use threads directly. std::async runs a function and hands you a std::future that will hold its result; calling .get() waits for it and returns the value, or rethrows whatever the task threw. There is no shared mutable state, so there is no race to reason about. A std::promise is the manual version for when a value is produced somewhere that is not a return statement.

#include <iostream>
#include <thread>
#include <mutex>
#include <atomic>
#include <future>
#include <vector>
#include <numeric>
#include <chrono>

int unsafe_counter{0};              // no protection - a data race

std::mutex       mtx;
int              guarded_counter{0};
std::atomic<int> atomic_counter{0};

void increment_unsafe(int times)
{
    for (int i = 0; i < times; ++i) { ++unsafe_counter; }   // UB
}

void increment_guarded(int times)
{
    for (int i = 0; i < times; ++i) {
        std::lock_guard<std::mutex> lock{mtx};   // locks here
        ++guarded_counter;
    }                                            // unlocks here, always
}

void increment_atomic(int times)
{
    for (int i = 0; i < times; ++i) { ++atomic_counter; }   // indivisible
}

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

int main()
{
    constexpr int per_thread = 100000;

    // ---------------- The race ----------------
    {
        std::thread t1{increment_unsafe, per_thread};
        std::thread t2{increment_unsafe, per_thread};
        t1.join();                 // join or detach before destruction,
        t2.join();                 // or the program terminates
        std::cout << "unsafe:  " << unsafe_counter
                  << " (expected " << per_thread * 2 << ")\n";
        // Prints something short of the expected number, differently
        // each run. Build with -fsanitize=thread and it is named for you.
    }

    // ---------------- Fixed with a mutex ----------------
    {
        std::thread t1{increment_guarded, per_thread};
        std::thread t2{increment_guarded, per_thread};
        t1.join();
        t2.join();
        std::cout << "mutex:   " << guarded_counter << '\n';   // exact
    }

    // ---------------- Fixed with an atomic, more cheaply ----------------
    {
        std::jthread t1{increment_atomic, per_thread};   // C++20: joins
        std::jthread t2{increment_atomic, per_thread};   // in its dtor
    }
    std::cout << "atomic:  " << atomic_counter << '\n';

    // ---------------- Usually the right answer: futures ----------------
    std::vector<int> data(1000000, 1);

    auto first  = std::async(std::launch::async, sum_range,
                             std::cref(data), 0u, data.size() / 2);
    auto second = std::async(std::launch::async, sum_range,
                             std::cref(data), data.size() / 2, data.size());

    long total = first.get() + second.get();   // .get() waits
    std::cout << "total:   " << total << '\n';

    // No shared mutable state, so no mutex and no race to reason about.
    // If sum_range threw, .get() rethrows it here - exceptions cross the
    // thread boundary, which they cannot do with a bare std::thread.

    // ---------------- promise/future, by hand ----------------
    std::promise<std::string> promise;
    std::future<std::string>  future = promise.get_future();

    std::jthread producer{[&promise] {
        std::this_thread::sleep_for(std::chrono::milliseconds{10});
        promise.set_value("produced elsewhere");
    }};

    std::cout << future.get() << '\n';   // blocks until set_value

    return 0;
}

Discussion

No questions on this topic yet. Sign in to ask the first one.