⚙️ C++ Intermediate

What is multithreading in C++?

Why Interviewers Ask This

Mid-level C++ roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

C++11 standardized the threading library (<thread>, <mutex>, <condition_variable>, <future>) for portable multithreaded programming. std::thread: #include <thread> void worker(int id) { std::cout << "Thread " << id << " running\n"; } int main() { std::thread t1(worker, 1); // Launch thread std::thread t2(worker, 2); t1.join(); // Wait for t1 to finish t2.join(); // join() or detach() required! }. Race conditions — use mutex: #include <mutex> std::mutex mtx; int counter = 0; void increment() { for (int i = 0; i < 1000; ++i) { std::lock_guard<std::mutex> lock(mtx); // RAII lock ++counter; // Protected critical section } // Lock automatically released }. std::lock_guard vs std::unique_lock: lock_guard — simpler, non-moveable, locks until scope ends; unique_lock — more flexible (defer lock, try_lock, timed_lock, usable with condition variables, moveable). Condition variables: std::condition_variable cv; std::mutex mtx; bool ready = false; // Producer: { std::unique_lock<std::mutex> lk(mtx); ready = true; cv.notify_all(); } // Consumer: std::unique_lock<std::mutex> lk(mtx); cv.wait(lk, []{ return ready; }); // Wait until ready. std::async and std::future: #include <future> auto fut = std::async(std::launch::async, [](int a, int b) { return a + b; }, 3, 4); int result = fut.get(); // Blocks until ready std::cout << result; // 7. std::atomic: lock-free atomic operations: std::atomic<int> counter{0}; counter++; // Thread-safe without mutex. Deadlock prevention: always acquire locks in the same order; use std::scoped_lock(m1, m2) (C++17) to lock multiple mutexes atomically.

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex C++ answers easy to follow.