Multithreading Basics in C++
std::thread (from <thread>) runs a function concurrently: std::thread t(work); launches, t.join() waits for completion — and every launched thread must be joined or detached before its object dies, or the program terminates. Threads share the whole address space, so unsynchronized access to shared data is a data race (undefined behavior), fixed with std::mutex plus lock_guard, or lock-free atomics (std::atomic).
Prefer higher-level tools where they fit: async/future for return values, parallel STL algorithms, or thread pools — raw threads plus manual mutexes are the assembly language of concurrency.
Launch and join
std::thread t(fn, args...); starts concurrent execution; t.join() blocks until it finishes — join every thread you start.
Shared memory races
Two threads touching one variable with at least one write and no ordering is undefined behavior — not just a wrong answer, any behavior.
mutex + lock_guard
std::lock_guard<std::mutex> lk(m); holds the lock for exactly its scope — exception-safe mutual exclusion in one line.
atomics for simple sharing
std::atomic<int> counters and flags synchronize without locks — cheaper and deadlock-free for single variables.
#include <iostream>#include <thread>#include <mutex> std::mutex m;int total = 0; void add(int n) { std::lock_guard<std::mutex> lk(m); total += n;} int main() { std::thread t1(add, 10); std::thread t2(add, 20); t1.join(); t2.join(); std::cout << total << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.