Learn C++
#include "advanced/multithreading.hpp"

Multithreading Basics in C++

//concept

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.

//how it works
1

Launch and join

std::thread t(fn, args...); starts concurrent execution; t.join() blocks until it finishes — join every thread you start.

2

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.

3

mutex + lock_guard

std::lock_guard<std::mutex> lk(m); holds the lock for exactly its scope — exception-safe mutual exclusion in one line.

4

atomics for simple sharing

std::atomic<int> counters and flags synchronize without locks — cheaper and deadlock-free for single variables.

//example
#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;
}
Output
30
1Two threads launch, each calling add with its own argument concurrently.
2The lock_guard serializes the total += n updates — no interleaving can lose an addition.
3Both joins complete before printing, so 10 + 20 = 30 is exact and deterministic.
//use cases
Parallelizing independent chunks (images, batches, simulations) across cores
Protecting shared counters and caches with mutex + lock_guard
Lock-free flags and counters with std::atomic
Reaching for async, thread pools, or parallel algorithms over raw threads

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.