Introduction & Syntax
Multithreading · Study material
Multithreading in C++ lets one program do several things at the same time: use every core of the CPU for heavy calculations, keep a user interface responsive while files download, or serve many network clients at once. Since C++11 the standard library has built-in threads (std::thread, C++20 std::jthread), synchronisation (std::mutex, std::condition_variable, std::atomic), and higher-level tools (std::async, std::future, and C++20 latches, barriers and semaphores). The hard part is correctness: two threads touching the same data without synchronisation is a data race – undefined behaviour that may work in testing and fail in production. This page explains each tool with programs whose output is deterministic, then tests you with 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.
On this page
- Creating threads, join and detach, passing arguments
- Data races and std::mutex with lock_guard, unique_lock, scoped_lock
- Deadlocks and how to avoid them
- std::atomic
- condition_variable and the producer–consumer pattern
- std::async, future and promise; std::jthread and stop tokens
- C++20 latch, barrier and counting_semaphore
Creating threads: std::thread, join and detach
Constructing a std::thread with a function (or lambda) and its arguments starts it immediately. Before the thread object is destroyed you must call join() (wait for it to finish) or detach() (let it run independently); destroying a joinable thread calls std::terminate. Prefer join – a detached thread may outlive the data it uses.
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>
void sum_range(const std::vector<int>& v, std::size_t from, std::size_t to, long& out) {
out = std::accumulate(v.begin() + from, v.begin() + to, 0L);
}
int main() {
std::vector<int> data(1'000'000);
std::iota(data.begin(), data.end(), 1); // 1 … 1,000,000
long left = 0, right = 0;
std::size_t mid = data.size() / 2;
// Each thread writes to its OWN variable: no shared mutable data, no race
std::thread t1(sum_range, std::cref(data), 0, mid, std::ref(left));
std::thread t2(sum_range, std::cref(data), mid, data.size(), std::ref(right));
t1.join(); // wait for both to finish
t2.join();
std::cout << left << " + " << right << " = " << left + right << '\n';
std::thread t3([] { /* a lambda works too */ });
std::cout << "joinable before join: " << t3.joinable() << '\n';
t3.join();
std::cout << "joinable after join: " << t3.joinable() << '\n';
return 0;
}
125000250000 + 375000250000 = 500000500000 joinable before join: 1 joinable after join: 0
Passing arguments
Arguments are copied into the new thread, even if the function takes a reference. Use std::ref/std::cref to pass a real reference (and make sure the object outlives the thread), and std::move for move-only arguments such as unique_ptr.
#include <iostream>
#include <memory>
#include <string>
#include <thread>
void by_value(std::string s) { s += "!"; }
void by_ref(std::string& s) { s += "!"; }
void take(std::unique_ptr<int> p) { *p += 1; }
int main() {
std::string a = "hi", b = "hi";
std::thread t1(by_value, a); // the thread gets its OWN copy
std::thread t2(by_ref, std::ref(b)); // std::ref: pass a real reference
t1.join(); t2.join();
std::cout << a << ' ' << b << '\n';
auto p = std::make_unique<int>(41);
std::thread t3(take, std::move(p)); // move-only arguments must be moved in
t3.join();
std::cout << (p == nullptr) << '\n';
return 0;
}
hi hi! 1
Data races and mutexes
A data race happens when two threads access the same memory at the same time, at least one of them writes, and nothing orders the accesses. Even ++counter is a read, an add and a write that can interleave. Protect shared data with a std::mutex, locked through an RAII guard: std::lock_guard (simple), std::unique_lock (can unlock early, needed for condition variables) or std::scoped_lock (several mutexes at once).
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
int main() {
long counter = 0;
std::mutex m;
auto work = [&] {
for (int i = 0; i < 100'000; ++i) {
std::lock_guard<std::mutex> lock(m); // only one thread at a time in here
++counter; // without the lock: a data race (undefined behaviour)
} // unlocked automatically, even on exceptions
};
std::vector<std::thread> pool;
for (int t = 0; t < 4; ++t) pool.emplace_back(work);
for (auto& t : pool) t.join();
std::cout << counter << '\n'; // always exactly 400000
return 0;
}
400000
std::atomic
For a single counter or flag, std::atomic<T> makes every read, write and read-modify-write (++, fetch_add, compare_exchange) indivisible – usually faster than a mutex. Atomics do not make a group of operations atomic; for invariants across several variables, use a mutex.
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
int main() {
std::atomic<long> hits{0}; // each operation is indivisible – no mutex needed
std::atomic<int> max_seen{0};
std::vector<std::thread> pool;
for (int t = 1; t <= 4; ++t)
pool.emplace_back([&hits, &max_seen, t] {
for (int i = 0; i < 50'000; ++i) hits.fetch_add(1, std::memory_order_relaxed);
int cur = max_seen.load();
while (t * 10 > cur && !max_seen.compare_exchange_weak(cur, t * 10)) {} // atomic "max"
});
for (auto& t : pool) t.join();
std::cout << hits.load() << ' ' << max_seen << ' ' << hits.is_lock_free() << '\n';
return 0;
}
200000 40 1
Deadlocks
A deadlock happens when threads wait for each other forever – typically thread 1 holds lock A and waits for B while thread 2 holds B and waits for A. Avoid it by always locking in the same global order, by locking several mutexes together with std::scoped_lock, by never calling unknown code while holding a lock, and by keeping critical sections short.
#include <iostream>
#include <mutex>
#include <thread>
struct Account {
std::mutex m;
long balance;
explicit Account(long b) : balance(b) {}
};
// Two threads transferring in opposite directions would deadlock if each locked "from" then "to".
// std::scoped_lock (C++17) locks several mutexes at once with a deadlock-avoidance algorithm.
void transfer(Account& from, Account& to, long amount) {
std::scoped_lock lock(from.m, to.m);
from.balance -= amount;
to.balance += amount;
}
int main() {
Account a(1000), b(1000);
std::thread t1([&] { for (int i = 0; i < 10'000; ++i) transfer(a, b, 1); });
std::thread t2([&] { for (int i = 0; i < 10'000; ++i) transfer(b, a, 2); });
t1.join(); t2.join();
std::cout << a.balance << ' ' << b.balance << ' ' << a.balance + b.balance << '\n';
return 0;
}
11000 -9000 2000
Condition variables: waiting for an event
A std::condition_variable lets a thread sleep until another thread signals that something changed. Always wait with a predicate (cv.wait(lock, [] { return condition; })), which re-checks the condition and handles spurious wake-ups. This is the basis of producer–consumer queues and thread pools.
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
class TaskQueue {
std::queue<int> q_;
std::mutex m_;
std::condition_variable cv_;
bool closed_ = false;
public:
void push(int v) {
{ std::lock_guard lock(m_); q_.push(v); }
cv_.notify_one(); // wake one waiting consumer
}
void close() {
{ std::lock_guard lock(m_); closed_ = true; }
cv_.notify_all();
}
bool pop(int& out) {
std::unique_lock lock(m_);
cv_.wait(lock, [this] { return !q_.empty() || closed_; }); // sleeps; the predicate handles spurious wake-ups
if (q_.empty()) return false; // closed and drained
out = q_.front();
q_.pop();
return true;
}
};
int main() {
TaskQueue q;
std::vector<long> done(3, 0); // one slot per consumer
std::vector<std::thread> consumers;
for (int c = 0; c < 3; ++c)
consumers.emplace_back([&q, &done, c] { for (int v; q.pop(v); ) done[c] += v; });
std::thread producer([&q] { for (int i = 1; i <= 100; ++i) q.push(i); q.close(); });
producer.join();
for (auto& t : consumers) t.join();
std::cout << "processed total " << done[0] + done[1] + done[2] << '\n'; // which consumer did what varies; the total does not
return 0;
}
processed total 5050
Tasks and futures: async, future, promise
Often you just want "run this in the background and give me the result". std::async returns a std::future; get() waits for the value – or rethrows the task's exception. std::promise is the "write end" of a future, for setting a value from any thread.
#include <future>
#include <iostream>
#include <numeric>
#include <stdexcept>
#include <thread>
#include <vector>
long long sum_squares(int from, int to) {
long long s = 0;
for (long long i = from; i <= to; ++i) s += i * i;
return s;
}
int main() {
// std::async: run a function and get its result later through a future
auto f1 = std::async(std::launch::async, sum_squares, 1, 500);
auto f2 = std::async(std::launch::async, sum_squares, 501, 1000);
std::cout << f1.get() + f2.get() << '\n'; // get() waits for the result
// Exceptions thrown in the task are delivered by get()
auto bad = std::async(std::launch::async, [] () -> int { throw std::runtime_error("task failed"); });
try { std::cout << bad.get(); } catch (const std::exception& e) { std::cout << "caught: " << e.what() << '\n'; }
// promise/future: one thread sets a value, another receives it
std::promise<std::string> ready;
std::future<std::string> msg = ready.get_future();
std::thread worker([&ready] { ready.set_value("config loaded"); });
std::cout << msg.get() << '\n';
worker.join();
return 0;
}
333833500 caught: task failed config loaded
std::jthread and cooperative cancellation (C++20)
std::jthread joins automatically in its destructor (no more forgotten join), and passes a std::stop_token to functions that accept one, so the owner can call request_stop() and the thread can finish cleanly.
#include <chrono>
#include <iostream>
#include <thread>
int main() {
int ticks = 0;
{
// jthread (C++20): joins automatically in its destructor and supports cooperative cancellation
std::jthread worker([&ticks](std::stop_token st) {
while (!st.stop_requested()) {
++ticks;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
});
std::this_thread::sleep_for(std::chrono::milliseconds(20));
worker.request_stop(); // ask it to finish…
} // …and the destructor joins it – no join() needed
std::cout << "worker stopped after " << (ticks > 0 ? "some" : "no") << " ticks\n";
return 0;
}
worker stopped after some ticks
Choosing a tool
| Need | Use |
|---|---|
| Run a function in parallel and get a result | std::async + std::future |
| A long-running background worker | std::jthread with stop_token |
| Protect shared data / invariants | std::mutex + lock_guard / scoped_lock |
| A single shared counter or flag | std::atomic |
| Wait until something happens | std::condition_variable (+ mutex) |
| Many readers, few writers | std::shared_mutex + shared_lock |
| Wait until N tasks are done | std::latch (C++20) |
| Phases where all threads must meet | std::barrier (C++20) |
| Limit concurrent access to N | std::counting_semaphore (C++20) |
| Per-thread data | thread_local |
| One-time initialisation | std::call_once or a function-local static |
Common mistakes
- Forgetting join() – a joinable std::thread destroyed → std::terminate.
- Unprotected shared data – data races are undefined behaviour, not just "wrong numbers".
- Passing references without std::ref – the thread modifies a copy.
- Dangling references – a detached thread using locals of a function that returned.
- Manual lock()/unlock() – an exception or early return leaves the mutex locked; use RAII guards.
- Locking in different orders – deadlock.
- Waiting on a condition variable without a predicate – lost or spurious wake-ups.
- Printing from many threads – output interleaves; collect results and print after joining.
Key points to remember
- Every std::thread must be joined or detached; std::jthread joins itself.
- Thread arguments are copied: std::ref for references, std::move for move-only types.
- Shared mutable data needs a mutex or atomics – or avoid sharing (each thread its own result).
- Lock with RAII: lock_guard, unique_lock, scoped_lock.
- Prevent deadlock with a fixed lock order or scoped_lock.
- Wait with condition_variable::wait(lock, predicate).
- std::async/future return values and exceptions from background tasks.
Frequently asked questions
What is the difference between concurrency and parallelism?
Concurrency is structuring a program as independent tasks that may overlap in time; parallelism is actually running them at the same instant on several cores.
How many threads should I create?
For CPU-bound work, about std::thread::hardware_concurrency() (the number of hardware threads); more only adds switching overhead. I/O-bound work can use more.
Are standard containers thread-safe?
Several threads may read the same container at once, but any writer requires all access to be synchronised.
Where can I learn more?
Read C++ Interview Questions, then practise with the exercises below.