Interview Q&A · C++ · 14 questions in this topic

Threads, Mutexes & Atomics — C++ Interview Q&A

All C++ topics

Writing correct concurrent C++ — threads, data races, mutexes, condition variables, atomics and futures. Part of Concurrency · 213 questions in the C++ bank.

How do you create and manage a `std::thread`?

Answer

Construct std::thread with a callable plus arguments; the new thread starts immediately. Every joinable thread must be joined (wait) or detached (release) before its destructor — destroying a joinable thread terminates. Prefer joining, wrap in RAII guards, and pass arguments by reference only with std::ref.

C++20 std::jthread improves this: it joins automatically and supports stop tokens.

Example

Example.cppcpp
#include <thread>
void work(int n) {}
std::thread t(work, 42);
// ...
t.join(); // must join or detach before t dies

What is a data race and why is it undefined behavior?

Answer

A data race is two unsynchronized accesses to the same memory with at least one write (and neither is atomic). In C++ it is undefined behavior — not merely a wrong value — so the compiler may assume races never happen and optimize accordingly, making symptoms unreproducible.

Fix with mutexes for compound operations or atomics for single locations; ThreadSanitizer finds races empirically.

Example

Example.cppcpp
int counter = 0;
// two threads: counter++ — data race (read-modify-write)!
std::atomic<int> safe{0};
// two threads: safe.fetch_add(1) — defined

💡 Say undefined behavior, not just wrong answer — the UB framing is what interviewers check.

What is a mutex and how do `lock_guard`, `unique_lock` and `scoped_lock` differ?

Answer

A mutex serializes access to shared data: lock before touching, unlock after. lock_guard is the simple scoped locker (no manual unlock, no flexibility). unique_lock adds unlock/relock, try-lock and condition-variable compatibility at slight cost. scoped_lock (C++17) locks multiple mutexes deadlock-free in one call.

Default to lock_guard; unique_lock only when you need its flexibility; scoped_lock for multi-mutex acquisition.

Example

Example.cppcpp
#include <mutex>
std::mutex m;
void add() {
    std::lock_guard<std::mutex> g(m); // auto-unlock, exception safe
    // touch shared data
}
void transfer(std::mutex& a, std::mutex& b) {
    std::scoped_lock both(a, b); // deadlock-free multi-lock
}

💡 Never call lock/unlock manually — the guard choice is the whole modern answer.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits