Learning Hub Search Ctrl K

Modern C++ › C++11

Threads, Mutexes and Atomics

std::thread, mutex, condition_variable, future and atomic.

Since C++11 advanced #threads#mutex#lock_guard#condition_variable#atomic#future#async#data-race

Explanation

C++11 adds a memory model and a standard threading library, so portable multithreaded code no longer depends on pthreads or Win32 APIs.

Component Header Purpose
std::thread <thread> start and join() / detach() a thread
std::mutex, lock_guard, unique_lock <mutex> mutual exclusion, with RAII locking
std::condition_variable <condition_variable> wait for a condition between threads
std::atomic<T> <atomic> lock-free (when possible) indivisible operations
std::async, std::future, std::promise <future> run a task and fetch its result or exception

A data race (two threads access the same memory, one writes, no synchronization) is undefined behavior. Prevent it with a mutex, an atomic, or by not sharing.

Always join or detach a std::thread before it is destroyed, otherwise std::terminate is called. Prefer std::lock_guard so a mutex is released even when an exception is thrown.

Example

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

int main() {
    // 1. mutex-protected shared counter
    int counter = 0;
    std::mutex m;
    auto work = [&] {
        for (int i = 0; i < 10000; ++i) {
            std::lock_guard<std::mutex> lock(m);      // unlocks at end of scope
            ++counter;
        }
    };
    std::thread t1(work), t2(work);
    t1.join(); t2.join();
    std::cout << "counter = " << counter << "\n";     // always 20000

    // 2. atomics: no mutex needed for a simple counter
    std::atomic<int> hits{0};
    std::vector<std::thread> pool;
    for (int i = 0; i < 4; ++i)
        pool.emplace_back([&hits] { for (int j = 0; j < 1000; ++j) ++hits; });
    for (auto& t : pool) t.join();
    std::cout << "hits = " << hits << "\n";           // 4000

    // 3. async/future: compute in the background, then collect the result
    std::future<long long> f = std::async(std::launch::async, [] {
        long long s = 0;
        for (int i = 1; i <= 1000000; ++i) s += i;
        return s;
    });
    std::cout << "sum = " << f.get() << "\n";         // waits if not finished
    return 0;
}

On GCC/Clang compile with -pthread.

Common pitfalls

  • A std::thread destroyed while still joinable calls std::terminate; join or detach every thread.
  • Capturing locals by reference in a detached thread: the locals may be gone when it runs.
  • Deadlock: two threads lock mutexes in opposite order. Lock them together with std::lock / std::scoped_lock (C++17).
  • condition_variable::wait needs a predicate (cv.wait(lock, [&]{ return ready; })) to handle spurious wake-ups.
  • std::atomic makes one operation atomic, not a sequence of them (if (x == 0) x = 1; is still a race).
  • Exceptions escaping a thread function terminate the program; catch inside the thread, or use std::async/future.

Legacy vs modern

C++98 has no thread concept at all: code used pthread_create, Win32 CreateThread, MFC AfxBeginThread, or Boost.Thread, each with different APIs. C++17 adds std::scoped_lock and shared_mutex; C++20 adds std::jthread (auto-join, stop tokens), std::latch, barrier, semaphore. See consteval, jthread and Other Additions.

Exercises

1. Why is ++counter on a plain int from two threads undefined behavior?

It is a read-modify-write that is not atomic: two threads can interleave and lose updates, and unsynchronized concurrent access is a data race.