Lesson 39 of 45
C++Lesson 39: Mutexes and Locks (std::mutex, std::lock_guard)
11 min
Course progress87%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 39 of 45
C++11 min
Keep these ideas in mind as you work through the lesson.
std::mutex, std::lock_guard)Mutual exclusion primitives protect shared data from concurrent access. std::mutex provides low‑level lock/unlock operations, while RAII wrappers like std::lock_guard and std::unique_lock ensure the lock is released even if an exception is thrown.
std::lock_guard#include <thread>
#include <mutex>
int counter = 0;
std::mutex mtx;
void increment(int times) {
for (int i = 0; i < times; ++i) {
std::lock_guard<std::mutex> lock(mtx);
++counter;
}
}
int main() {
std::thread t1(increment, 1000);
std::thread t2(increment, 1000);
t1.join();
t2.join();
std::cout << \"Final counter: \" << counter << '\
';
return 0;
}
std::unique_lock for more flexibilitystd::unique_lock<std::mutex> lock(mtx, std::defer_lock);
// ... perform some work without holding the lock
lock.lock(); // acquire later
// critical section
lock.unlock(); // release early if needed
Tip: Prefer
std::scoped_lock(C++17) when you need to lock multiple mutexes atomically.
<Alert type="info">Deadlocks occur when two threads acquire the same mutexes in opposite order. Use a consistent lock acquisition order or std::scoped_lock to avoid.