Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Part 5: Concurrency, Lambda & Top Gotchas
C++

Part 5: Concurrency, Lambda & Top Gotchas

Revise C++ threads, mutexes, atomics, lambda expressions, synchronization, and common language pitfalls.

1. Threads

  • std::threadstd::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::mutex via std::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/notify for 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.
  • atomic operations default to seq_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 (sort comparators, find_if predicates).

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::move doesn’t move; it casts to rvalue.
  • Mixing signed/unsigned — comparisons/arithmetic wrap or surprise.
  • sizeof on pointers changes meaning for arrays in exceptions.
  • std::endl flushes — 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.

My Private Notes

Notes are auto-saved locally to this device.