skip to content

Concurrency Support

The standard library gives C++ threads, mutexes, condition variables, atomics, futures and coroutines. Interviewers ask about data races, memory order and deadlock-free locking.

on this pageshow

explore

questions

page 1 of 2

In C++, what goes wrong when two threads run ++count on a shared plain int, and what does std::atomic<int> change?

level: juniorimportance: must knowfreq 78%

answer

  1. load, add, store
  2. data race means undefined behavior
  3. one indivisible read-modify-write
  4. ++ is fetch_add underneath
  5. a = a + 1 is two operations

basics

~20 s

Two threads incrementing a plain int without synchronisation is a data race, which C++ makes undefined behavior; in practice increments get lost. On std::atomic<int>, ++count is one indivisible read-modify-write (fetch_add), so no increment is lost.

solid answer

~40 s

`++count` is a load, an add and a store. On a plain `int`, two threads doing that concurrently is a **data race** — two conflicting accesses, at least one not atomic, neither happening before the other — and the standard makes any data race undefined behavior, not just a wrong total. In practice both threads read the same old value and both store old+1, and the optimiser may keep the counter in a register. On `std::atomic<int>`, `++count` is one atomic read-modify-write, equivalent to `fetch_add(1) + 1`, with `memory_order::seq_cst` by default, so every increment lands. The trap is `count = count + 1` on the atomic: that is an atomic load and then a separate atomic store, race-free but still able to lose increments.

code

cpp · 20 lines
cpp
#include <atomic>
#include <cstdio>
#include <thread>

std::atomic<int> hits{0};
std::atomic<int> split{0};

void work() {
    for (int i = 0; i < 100000; ++i) {
        ++hits;               // one atomic read-modify-write: fetch_add(1)
        split = split + 1;    // an atomic load, then a separate atomic store
    }
}

int main() {
    std::thread a(work), b(work);
    a.join();
    b.join();
    std::printf("hits=%d split=%d\n", hits.load(), split.load());
}

go deeper

for a junior

Say the words data race and undefined behavior, and show that ++ on a std::atomic<int> is one indivisible read-modify-write that never loses an increment.

for a middle

Explain why a = a + 1 and check-then-act code still lose updates on an atomic, and name fetch_add and the seq_cst default behind the operators.

for a senior

Show how the optimiser exploits a race on a plain int, why the result has no defined output, and how a race detector confirms the bug before any fix is trusted.

for a principal

Treat every shared counter as a design decision: an atomic for independent counts, a mutex when the update spans several variables, and code review rules that reject unsynchronised shared writes.

## What `++count` really is On a plain `int`, the expression `++count` is not one step. The machine **loads** the current value, **adds** one and **stores** the result. Two threads that interleave those steps can both load 41, both compute 42 and both store 42: one increment vanishes. That is the everyday symptom, and it is why the total of 200,000 increments from two threads comes out lower and different on every run. ## Why the standard calls it undefined behavior C++ does not describe the lost update as "a wrong number". The standard defines a **data race**: two potentially concurrent **conflicting** actions on the same memory location (at least one of them a write), at least one of which is **not atomic**, where neither **happens before** the other. It then says plainly that any data race results in **undefined behavior**. Consequences that follow from that rule: - **Lost updates** are only the mild case. - The compiler may assume no other thread touches a non-atomic object without synchronisation, so it can keep `count` in a register for the whole loop, or fold 100,000 increments into a single `add`. - For types wider than the machine word, a reader can observe a **torn** value that no thread ever wrote. - Because the behavior is undefined, there is no "expected wrong answer" to reason about; a program with a race has no guaranteed output at all. ## What `std::atomic<int>` changes `std::atomic<int>` turns every access to the object into an **atomic operation**: indivisible with respect to every other atomic access to the same object, and never part of a data race. | Expression on `std::atomic<int> a` | What it is | Can it lose an increment? | |---|---|---| | `++a`, `a++` | `fetch_add(1)` — one read-modify-write | no | | `a += 1` | `fetch_add(1) + 1` | no | | `a.fetch_add(1)` | one read-modify-write, returns the old value | no | | `a = a + 1` | `a.load()`, then a separate `a.store(...)` | yes | | `int v = a;` | `a.load()` | — | Two rules make the first three rows safe. A read-modify-write must read the **last value in the modification order** of the object, so two `fetch_add` calls can never both see 41. And the operators use **`memory_order::seq_cst`** unless you call the member function with a weaker order yourself. ## The two-step trap The last row is the classic mistake. `a = a + 1` compiles, raises no warning and has no data race, because both the load and the store are atomic. But another thread can increment between them, and the store then overwrites that increment. The same shape hides in **check-then-act** code: ```cpp if (a < limit) ++a; // the check and the increment are separate operations ``` Two threads can both pass the check at `limit - 1` and both increment. When the update depends on the current value, use one read-modify-write (`fetch_add`, `fetch_sub`, `exchange`) or a `compare_exchange_weak` loop, which is covered with compare-and-exchange. ## Seeing it on a real compiler 1. Build the example below with `-std=c++17 -O2` and run it a few times: `hits` is always 200000, `split` is lower and changes from run to run. 2. Add a plain `int` incremented the same way and build with `-fsanitize=thread`: ThreadSanitizer, covered with the sanitizers, reports `WARNING: ThreadSanitizer: data race` with both threads' stacks. 3. Remove the plain `int` again before trusting any output, because a program with a data race has no defined output. ## What `std::atomic<int>` does not do - It does not make a **sequence** of operations atomic; only each single operation is. - It does not protect any **other** variable; ordering other memory is what memory orders are for. - It is not copyable: the copy constructor and copy assignment are deleted, so you read the value with `load()` and write it with `store()`.

  • Does std::atomic<int> make if (count < limit) ++count; safe?
    No. The comparison is one atomic load and the increment is a second atomic operation, so two threads can both see `limit - 1`, both pass the check and both increment. Either do the whole decision in a `compare_exchange_weak` loop that only stores when the value it read is still below the limit, or protect the check and the increment with one mutex.
  • Why can't you copy a std::atomic<int> into another one?
    `std::atomic`'s copy constructor and copy assignment are deleted. Copying one atomic into another would be a load from the first and a store into the second — two operations on two objects — and no single atomic operation covers both. You write the intent explicitly: `std::atomic<int> b{a.load()};` or `b.store(a.load());`, which makes the non-atomic pair visible in the code.

  • A race on an int only makes the count a little low, nothing worse.
  • count = count + 1 on a std::atomic<int> is as safe as ++count.
  • Incrementing an int is one instruction, so another thread cannot interleave with it.
  • Marking the shared int volatile makes each increment atomic.
  • Making the counter atomic also makes the plain variables written next to it race-free.
open as a page

In C++, why is a std::mutex locked through std::lock_guard rather than by calling lock() and unlock() directly?

level: juniorimportance: must knowfreq 78%

basics

~20 s

std::lock_guard locks the mutex in its constructor and unlocks it in its destructor, so the mutex is released on every way out of the scope, including exceptions and early returns. A manual unlock() call is skipped by those paths and leaves the mutex locked.

open as a page

In C++, what happens when a std::thread object is destroyed while still joinable, and how do join() and detach() prevent it?

level: juniorimportance: must knowfreq 80%

basics

~20 s

The std::thread destructor calls std::terminate if the object is still joinable. Before it is destroyed, call join() to wait for the thread to finish or detach() to let it run on independently; both leave the object non-joinable.

open as a page

In C++, what does std::condition_variable::wait(lock, pred) guarantee when it returns, and why prefer it to a bare wait(lock)?

level: middleimportance: must knowfreq 72%

basics

~20 s

wait(lock, pred) is specified as while (!pred()) wait(lock);, so it returns only with the mutex held and pred() true. It absorbs spurious wake-ups and never blocks when the condition already holds; a bare wait(lock) can return with the condition false.

open as a page

In C++, what does std::async do when called without a launch policy, and why can a wait_for polling loop then spin forever?

level: middleimportance: must knowfreq 66%

basics

~20 s

Without a policy std::async uses launch::async | launch::deferred and the implementation chooses. A deferred task runs only when get() or wait() is called, in the caller's thread, and wait_for returns future_status::deferred, never ready, so a polling loop never ends.

open as a page

In C++, how do you lock the std::mutex of two inventory records for a stock transfer without risking deadlock?

level: middleimportance: must knowfreq 66%

basics

~10 s

Lock both with one call that avoids deadlock: std::scoped_lock lock(from.mu, to.mu) in C++17, or std::lock(from.mu, to.mu) followed by two lock_guards with std::adopt_lock in C++11. Guard against transferring a record to itself first.

open as a page

Why does std::thread t(encode, id, stats) fail to compile when encode takes SegmentStats&, and what does std::ref change?

level: middleimportance: must knowfreq 68%

basics

~20 s

std::thread copies or moves every argument into storage the new thread owns and passes those copies as rvalues, which a SegmentStats& parameter cannot bind. std::ref(stats) passes a copyable reference_wrapper that converts back to a reference to the original.

open as a page

A C++ thumbnail generator calls std::async(std::launch::async, make_thumbnail, img) in a loop, keeping each future only for that iteration; why does it run sequentially?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Each iteration's std::future dies at the end of the loop body, and the last future of an unfinished std::async task may block in its destructor until the task ends, as libc++ and libstdc++ do. Keep the futures and get() them after the loop.

open as a page

In C++, why does std::condition_variable::wait take a std::unique_lock<std::mutex> and refuse a std::lock_guard?

level: juniorimportance: should knowfreq 52%

basics

~10 s

std::condition_variable::wait must release the mutex while the thread sleeps and lock it again before returning, so it takes a std::unique_lockstd::mutex, which can unlock and relock. std::lock_guard cannot, so the call does not compile.

open as a page

In C++, how does std::future::get deliver a std::async task's result or exception, and why can it be called only once?

level: juniorimportance: should knowfreq 58%

basics

~20 s

std::future::get waits until the shared state is ready, then moves the stored value out or rethrows the stored exception. It releases the state, so valid() becomes false and a second get() is undefined; std::shared_future allows repeated get().

open as a page

In C++, when is memory_order_relaxed enough for an atomic statistics counter, and what exactly does relaxed give up?

level: middleimportance: should knowfreq 50%

basics

~20 s

Relaxed is enough when the counter's value is the only thing anyone needs: increments stay atomic and none are lost. It gives up ordering of all other memory, so a relaxed counter must never signal that other data is ready.

open as a page

In C++20, how do std::latch, std::barrier and std::counting_semaphore differ, and which one releases a group of test threads at once?

level: middleimportance: should knowfreq 40%

basics

~20 s

std::latch is a single-use countdown: count_down to zero releases every waiter, so a latch of 1 is a start gate for test threads. std::barrier repeats in phases and runs a completion function; std::counting_semaphore counts permits with acquire and release.

open as a page

In C++, what does co_yield do in a lazy generator of log lines, and what does C++23's std::generator add over a hand-written one?

level: middleimportance: should knowfreq 38%

basics

~20 s

co_yield e means co_await promise.yield_value(e): the promise stores the value and the coroutine suspends until the consumer asks for the next one. C++23's std::generator packages that promise, an input iterator and frame ownership into a ready-made lazy range.

open as a page

In C++20, what turns an ordinary function into a coroutine, and how does the compiler find the promise_type that drives it?

level: middleimportance: should knowfreq 42%

basics

~10 s

A function is a coroutine if its body contains co_await, co_yield or co_return; its declaration looks unchanged. The compiler uses std::coroutine_traits<R, Args...>::promise_type, which by default is the return type's nested promise_type.

open as a page

In C++, how do std::promise and std::packaged_task each connect a result to a std::future, and how does an exception reach the caller?

level: middleimportance: should knowfreq 45%

basics

~20 s

A std::promise is set by hand with set_value or set_exception; a std::packaged_task wraps a callable and stores its return value or exception when called. get() rethrows a stored exception; a provider destroyed unset stores broken_promise.

open as a page

In C++, how does std::call_once with a std::once_flag initialize shared data exactly once, and what happens if the initializer throws?

level: middleimportance: should knowfreq 40%

basics

~20 s

std::call_once(flag, f) lets one caller at a time run f until a run returns normally; other callers wait, and every later call returns without running f but sees its results. If f throws, that caller gets the exception and a later call retries.

open as a page

For a read-mostly C++ stock catalog, how do std::shared_mutex and std::shared_lock work, and when do they fail to pay off?

level: middleimportance: should knowfreq 48%

basics

~20 s

std::shared_mutex (C++17) lets many threads hold shared ownership for reading while exclusive ownership excludes everyone. Readers lock through std::shared_lock, writers through std::unique_lock or lock_guard. It pays off when read sections are long and contended enough to outweigh its higher per-acquisition cost.

open as a page

In C++, when do you need std::unique_lock instead of std::lock_guard, and what does its extra flexibility cost?

level: middleimportance: should knowfreq 58%

basics

~20 s

Use std::unique_lock when the lock must do more than lock for a whole scope: defer or try locking, time out on a timed mutex, unlock early, or move ownership elsewhere. It costs an ownership flag checked in the destructor and more room for misuse.

open as a page

What does C++20 std::jthread do differently from std::thread, and how does a worker function receive and use its std::stop_token?

level: middleimportance: should knowfreq 52%

basics

~10 s

C++20 std::jthread owns a stop_source; its destructor calls request_stop() and then join() instead of terminating. If the function's first parameter accepts a std::stop_token, jthread passes one, and the worker polls stop_requested() to exit cooperatively.

open as a page

In a C++ worker thread, what does a thread_local variable give each thread, and when is it constructed and destroyed?

level: middleimportance: should knowfreq 45%

basics

~20 s

A thread_local variable has a distinct object in every thread that uses it. A block-scope one is initialized the first time each thread passes its declaration, and each thread's constructed objects are destroyed when that thread's initial function returns.

open as a page

In a C++ single-producer single-consumer audio ring buffer, why must the head index be stored with release and loaded with acquire, and what breaks if both are relaxed?

level: seniorimportance: should knowfreq 55%

basics

~20 s

The producer writes the sample into a plain buffer slot, then stores head with release; the consumer loads head with acquire. That pairing makes the slot write happen before the consumer's read. With relaxed, the buffer access is a data race.

open as a page

In C++, why is compare_exchange_weak normally called in a loop, and when should you prefer compare_exchange_strong instead?

level: seniorimportance: should knowfreq 52%

basics

~20 s

compare_exchange_weak may fail spuriously even when the value matches, so it only makes sense where a failure is retried anyway. On failure it writes the current value back into expected. Use compare_exchange_strong when a single attempt decides something.

open as a page

A C++ producer sets a std::atomic<bool> flag without locking the mutex, then calls notify_one; why can the waiting consumer still block forever?

level: seniorimportance: should knowfreq 42%

basics

~20 s

The consumer can read the flag as false and then block; a store and notify_one landing between those two steps find no blocked thread, so the notification is lost. Storing the flag under the waiter's mutex closes that window.

open as a page

In C++20, what happens step by step at co_await on an awaiter for an async socket read, and what may await_suspend return?

level: seniorimportance: should knowfreq 40%

basics

~20 s

co_await calls await_ready; if it returns false the coroutine suspends and await_suspend(handle) runs, typically starting the read and storing the handle. When something resumes the handle, await_resume's result becomes the value of the co_await. await_suspend may return void, bool or a coroutine_handle.

open as a page

A lazy C++20 coroutine takes const std::string& and is resumed after the caller's temporary has died; why does it read freed memory, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

The frame copies parameters, but a reference parameter is copied as a reference to the caller's object. A temporary passed to it dies at the end of the call's full-expression, so a later resume reads a destroyed string. Take the parameter by value instead.

open as a page

A C++ inventory class hangs when one locked member function calls another that locks the same std::mutex; why, and is std::recursive_mutex the fix?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Relocking a std::mutex the thread already owns breaks lock()'s precondition: undefined behaviour, usually a self-deadlock. std::recursive_mutex makes it legal, but the usual fix splits each operation into a locking public function and a private helper that assumes the lock.

open as a page

A C++20 transcoder worker is blocked in read() and cannot poll its std::stop_token; how does std::stop_callback let a cancel request unblock it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

A std::stop_callback on the worker's token runs its callable on the first request_stop(), synchronously on the requesting thread, or at once in its constructor if a stop was already requested. The callable unblocks the read, for example by closing the pipe's write end.

open as a page

As the lead of a C++ codebase, when do you allow hand-written lock-free code with explicit memory orders, and what conditions do you attach?

level: principalimportance: should knowfreq 40%

basics

~20 s

Allow it only where a measured latency or blocking requirement rules out a mutex, confined to a small reviewed primitive. Require the seq_cst default unless a comment justifies each weaker order, ThreadSanitizer runs, testing on a weakly ordered CPU and a named reviewer.

open as a page

As a C++ lead, how do you decide whether and how your team adopts C++20 coroutines when the standard library supplies no task type or executor?

level: principalimportance: should knowfreq 28%

basics

~20 s

Adopt only with one owned or vetted task type, a scheduler story and lifetime rules the team enforces. C++20 gives the language and handles, C++23 only std::generator, and C++26's std::execution::task is missing from libc++ (LLVM 23) and libstdc++ (GCC 16.2).

open as a page

Your C++ codebase launches background work with std::async everywhere; would you ban it in favour of a thread pool, and what would you standardise instead?

level: principalimportance: should knowfreq 30%

basics

~20 s

Usually restrict rather than ban: std::async cannot cap thread count, may defer by default, starts a thread per call in libc++ and libstdc++, and hides waits in destructors. Route frequent work through one owned pool; keep launch::async for rare coarse tasks.

open as a page

showing 1–30 of 33