Mutexes & Condition Variables
Prerequisites: Concurrency with std::thread
std::mutex protects shared data from simultaneous access by
multiple threads; std::lock_guard applies RAII to locking, so the
mutex is released automatically — even if an exception is thrown —
rather than needing a manual unlock:
#include <mutex>
std::mutex mtx;
int counter = 0;
void increment() {
std::lock_guard<std::mutex> lock(mtx); // locked here
counter++;
} // automatically unlocked here, whatever happens
std::condition_variable cv;
bool ready = false;
void waitForReady() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return ready; }); // sleeps until notified AND ready
}
A condition variable lets a thread sleep efficiently until another thread signals a change, rather than repeatedly checking a flag in a busy loop.
Common mistakes
- Locking a mutex manually with
.lock()/.unlock()instead ofstd::lock_guard— an exception thrown between the two leaves the mutex locked forever, deadlocking every other thread that needs it.