C++C++ Explainer
C++ · 6 · Concurrency25 / 36 · 69%

std::thread & std::mutex

Portable concurrency in the standard library.

shortcuts: ← prev · → next · M mark
1

std::thread

Create a thread with a callable and its arguments.

Example
example
#include <thread>

void worker(int id) { std::cout << "hi " << id << '\n'; }

int main() {
    std::thread t1(worker, 1);
    std::thread t2(worker, 2);
    t1.join();
    t2.join();
}
mainthread 1worker()thread 2worker()thread 3worker()
two workers
2

std::mutex + lock_guard

RAII lock — releases even on exception.

Example
example
std::mutex m;
int counter = 0;

void inc() {
    for (int i = 0; i < 100000; ++i) {
        std::lock_guard<std::mutex> lk(m);
        ++counter;
    }
}
3

std::atomic

Lock-free counters / flags for hot paths.

Example
example
#include <atomic>
std::atomic<int> hits{0};
hits.fetch_add(1, std::memory_order_relaxed);
4

async & future

Fire-and-collect concurrent tasks.

Example
example
#include <future>
auto f = std::async(std::launch::async, [] { return 42; });
int v = f.get();   // waits and retrieves