Concurrency & Threads

std::thread, mutex, lock_guard, atomics and std::async.

Advanced
Key PointsAlways lock mutexes via RAII guards (lock_guard/unique_lock), never raw lock/unlock.
C++
#include <thread>
#include <mutex>
#include <atomic>
#include <iostream>

std::mutex m;
int counter = 0;

void bump() {
    for (int i = 0; i < 10000; ++i) {
        std::lock_guard lock(m);
        ++counter;
    }
}

int main() {
    std::thread t1(bump), t2(bump);
    t1.join(); t2.join();
    std::cout << counter << '\n';  // 20000
}

For plain counters prefer std::atomic<int> over a mutex - it is lock-free.

Friends & Partners