Multithreading and Concurrency Interview Questions for C++
25 Multithreading and Concurrency questions with answers for c++ roles — 7 easy, 11 medium, 7 hard.
About Multithreading and Concurrency
Write safe multithreaded code with std::thread, jthread, mutexes, locks, condition variables, atomics, futures and thread pools. Learn to recognise and fix data races, deadlocks and false sharing, and design producer-consumer pipelines and lock-free queues used in servers, trading systems and real-time applications.
Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
What is the difference between a process and a thread?
A process is an independent program with its own address space, file handles and resources; processes are isolated and communicate through IPC such as pipes, sockets or shared memory. Threads live inside a process and share its memory and handles, but each has its own stack and registers. Threads are cheaper to create and communicate faster, but shared memory needs synchronisation to avoid races.
02
How do you create a thread in C++ and what is the difference between join and detach?
std::thread t(func, args); starts a new thread running func. join() blocks until the thread finishes, so the caller can safely use its results. detach() lets the thread run independently; you lose the handle and it must not touch objects that may be destroyed. If a joinable std::thread is destroyed without join or detach, std::terminate is called. C++20 std::jthread joins automatically in its destructor.
A data race occurs when two threads access the same memory at the same time, at least one writes, and there is no synchronisation; in C++ this is undefined behaviour. A race condition is a broader logic bug where the result depends on timing, such as check-then-act on a file or a balance, even if each access is atomic. Mutexes, atomics and careful design of shared state prevent both.
04
Four threads each increment a shared int one million times, but the final total is less than four million. Why?
counter++ is a read-modify-write of three steps, so threads interleave and overwrite each other's updates, which is a data race and undefined behaviour. Fix it with std::atomic<int> and fetch_add, which is fast for a simple counter, or protect the variable with a mutex. Even better for performance, let each thread count in a local variable and add it to the total once at the end.
Situation: at 2 AM our order service started timing out. Task: restore service quickly and find the cause. Action: I followed the runbook, checked dashboards, saw thread pool saturation after a new release, rolled back within 15 minutes and posted updates in the incident channel. Next day I found a blocking database call inside a worker thread. Result: service was restored fast, and I added a timeout and an alert on queue depth.
07
Tell me about a time you worked with QA to fix a flaky test.
Situation: a multithreaded integration test failed about once in twenty runs and QA kept reopening the ticket. Task: make it reliable without hiding a real bug. Action: I sat with the QA engineer, ran the test in a loop with logging, and saw it used sleep to wait for a worker. I replaced the sleep with a condition variable signal and fixed a small real race we found. Result: 1000 consecutive passes and better trust between dev and QA.
08
Compare std::mutex, lock_guard, unique_lock and scoped_lock.
std::mutex provides lock and unlock, but calling them manually is error-prone. lock_guard is a simple RAII wrapper that locks in the constructor and unlocks in the destructor. unique_lock is more flexible: it can defer locking, unlock early, be moved and is required by condition_variable. scoped_lock, from C++17, locks one or more mutexes at once using a deadlock-avoidance algorithm.
A deadlock happens when threads wait forever for each other's locks, for example thread A holds m1 and waits for m2 while thread B holds m2 and waits for m1. It needs mutual exclusion, hold and wait, no preemption and circular wait. Prevent it by always locking in a fixed global order, locking several mutexes together with std::scoped_lock, keeping critical sections small and never calling unknown code while holding a lock.
10
How does std::condition_variable work and what are spurious wakeups?
A condition variable lets a thread sleep until another thread signals that some state changed. The waiter holds a unique_lock and calls cv.wait(lock, predicate), which releases the mutex while sleeping and reacquires it on wake. The notifier changes the state under the mutex and calls notify_one or notify_all. Threads can wake without notification, called spurious wakeups, so always wait with a predicate that rechecks the condition.
std::async runs a function, possibly on another thread, and returns a std::future that will hold its result or exception; calling get() waits for it. Use std::launch::async to force a new thread. std::promise is the writing end: one thread calls set_value or set_exception, and the paired future receives it. They make simple fork-join tasks easier than manual threads, but are not a full thread pool.
12
What does C++20 std::jthread add over std::thread?
std::jthread joins automatically in its destructor, so forgetting join no longer calls std::terminate. It also supports cooperative cancellation: the thread function can take a std::stop_token, check stop_requested() in its loop, and the owner calls request_stop(), which the destructor also does before joining. std::stop_callback lets you register cleanup actions. This makes long-running worker threads safer to write.
13
A service occasionally freezes and thread dumps show two threads each waiting on a mutex held by the other. How do you fix it?
This is a lock-order deadlock. I would find the two code paths, for example transfer locking account A then B while another locks B then A. The fix is to lock both together with std::scoped_lock(a.m, b.m), or to define a global ordering such as by account ID and always lock lower first. I would also shrink critical sections and add a stress test, and consider TSan or lock hierarchy checks.
14
Design a producer-consumer pipeline where one thread reads log lines and several workers parse them.
I would use a bounded thread-safe queue built with a mutex and two condition variables, one for not empty and one for not full, so a fast reader cannot exhaust memory. The reader pushes lines and workers pop and parse them. For shutdown, the reader pushes a sentinel per worker or sets a closed flag and notifies all. Batching lines per push reduces locking overhead, and results go to a second queue.
15
A program crashes with terminate called without an active exception when a function returns. What is the cause?
A std::thread object that is still joinable was destroyed, often because the function returned early or threw before reaching join. The std::thread destructor calls std::terminate in that case. Fix it by making sure every thread is joined on all paths, using an RAII guard, or switching to std::jthread, which joins automatically. Be careful with detach, since detached threads may access destroyed data.
16
Write a program where two threads print odd and even numbers alternately up to 10.
#include <future>
#include <numeric>
#include <vector>
long long parallelSum(const std::vector<int>& v, int parts = 4) {
std::vector<std::future<long long>> futs;
std::size_t chunk = v.size() / parts;
for (int i = 0; i < parts; ++i) {
auto b = v.begin() + i * chunk;
auto e = (i == parts - 1) ? v.end() : b + chunk;
futs.push_back(std::async(std::launch::async, [b, e] {
return std::accumulate(b, e, 0LL);
}));
}
long long total = 0;
for (auto& f : futs) total += f.get();
return total;
}
// C++17 alternative: std::reduce(std::execution::par, v.begin(), v.end(), 0LL)
18
Write a deadlock-free money transfer between two bank accounts.
std::atomic<T> makes reads, writes and read-modify-write operations such as fetch_add indivisible and race-free without a mutex. Memory order controls how other memory operations are ordered around it. seq_cst, the default, gives one global order and is easiest to reason about. acquire and release pair up to publish data from one thread to another. relaxed only guarantees atomicity, suitable for simple counters. Weaker orders are faster but harder to get right.
20
You parallelised a loop across eight threads but it became slower than the single-threaded version. What could be wrong?
Likely causes are lock contention when all threads share one mutex, false sharing when per-thread counters sit on the same 64-byte cache line, too little work per task so thread creation dominates, or memory bandwidth limits. I would profile with perf, pad per-thread data with alignas(64) or std::hardware_destructive_interference_size, use thread-local accumulation and a thread pool, and make chunks larger.
21
Many threads read a shared configuration object constantly, but it changes only once an hour. How do you synchronise it efficiently?
A plain mutex would serialise all readers. Option one is std::shared_mutex: readers take shared_lock and run in parallel, the updater takes unique_lock. Option two, often faster, is to keep the config in a std::shared_ptr<const Config> and swap in a new immutable object atomically with std::atomic<std::shared_ptr> in C++20; readers grab a copy of the pointer and never block the writer.
22
A low-latency system needs a queue between two threads with no locks. How would you approach it?
For one producer and one consumer, a single-producer single-consumer ring buffer is the standard answer: a fixed-size array with atomic head and tail indices, using release on publish and acquire on read, and padding so the indices sit on different cache lines. It avoids allocation and syscalls. For multiple producers I would use a proven library rather than writing my own, and verify with stress tests and TSan.
Situation: a market data service dropped a few updates per day only under heavy load. Task: find the cause without disrupting trading hours. Action: I wrote a stress harness replaying recorded traffic, ran it under ThreadSanitizer and found two threads updating a shared index without synchronisation. I redesigned it to a single-writer model with an SPSC queue. Result: zero dropped updates over a month and latency improved slightly because locks were removed.
Frequently asked questions
How important is Multithreading and Concurrency in C++ interviews?
Write safe multithreaded code with std::thread, jthread, mutexes, locks, condition variables, atomics, futures and thread pools. Learn to recognise and fix data races, deadlocks and false sharing, and design producer-consumer pipelines and lock-free queues used in servers, trading systems and real-time applications.
How should I use the Multithreading and Concurrency sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.