1. Threads
std::thread—std::thread t(f, args);join()to wait, else program terminates if t is joinable and destroyed.
std::thread t([] { std::cout << "hi\n"; });
t.join(); // required before thread object exits scope
std::jthread(C++20) auto-joins on destroy and supports cooperative cancellation.
2. Synchronization
std::mutexviastd::lock_guard/std::unique_lock— RAII for locking.std::atomic<T>for lock-free scalars.
std::mutex m;
int count = 0;
void inc() {
std::lock_guard<std::mutex> lock(m); // locked/unlocked automatically
++count;
}
- std::atomic for counters/booleans used across threads; no locks needed.
std::condition_variable+wait/notifyfor event coordination.
3. Data races & memory ordering
- A data race = two threads, at least one writes, same location, unsynchronized → UB.
- Rule: no unprotected shared mutable state.
atomicoperations default toseq_cst(strongest ordering, easiest to reason).
4. Lambdas
auto add = [](int a, int b) { return a + b; };
int base = 10;
auto byRef = [&base](int x) { return x + base; }; // capture by ref
auto byVal = [base](int x) { return x + base; }; // capture by value
- Capture
[](nothing),[x](value),[&](ref),[=, &y](all value except y ref). - Mutable lambda when you need to modify a captured-by-value variable.
- Widely used with algorithms (
sortcomparators,find_ifpredicates).
5. Gotcha sheet — interview fast-refresh
- Sequence/UB: modification of same scalar without ordering — always race.
- Dangling references: returning a reference/pointer to a local.
- Copy vs reference capture of loop var — classic capture-by-ref bug.
vector<bool>is not a vector of bool — proxied,&v[i]is ill-formed for a proxy.std::movedoesn’t move; it casts to rvalue.- Mixing signed/unsigned — comparisons/arithmetic wrap or surprise.
sizeofon pointers changes meaning for arrays in exceptions.std::endlflushes — prefer'\n'.
6. Interview checkpoint
- thread join semantics; jthread benefit.
- lock_guard vs unique_lock (flavours of RAII).
- Atomic vs mutex for counters.
- Lambda capture rules —
[&]vs[=]and the dangling capture trap. - The gotcha sheet — review carefully before any C++ exam.
Premium Content
Unlock Part 5: Concurrency, Lambda & Top Gotchas and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans