Lesson 33 of 45 · C++
Lesson 39: Mutexes and Locks (std::mutex, std::lock_guard)
Duration: 11 min
Lesson 33 of 45 · C++
Duration: 11 min
std::mutex, std::lock_guard)\n\nMutual 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.\n\n---\n\n## Example: Protecting a shared counter with std::lock_guard\ncpp\n#include <thread>\n#include <mutex>\n\nint counter = 0;\nstd::mutex mtx;\n\nvoid increment(int times) {\n for (int i = 0; i < times; ++i) {\n std::lock_guard<std::mutex> lock(mtx);\n ++counter;\n }\n}\n\nint main() {\n std::thread t1(increment, 1000);\n std::thread t2(increment, 1000);\n t1.join();\n t2.join();\n std::cout << \"Final counter: \" << counter << '\\n';\n return 0;\n}\n\n\n## std::unique_lock for more flexibility\ncpp\nstd::unique_lock<std::mutex> lock(mtx, std::defer_lock);\n// ... perform some work without holding the lock\nlock.lock(); // acquire later\n// critical section\nlock.unlock(); // release early if needed\n\n\n> Tip: Prefer std::scoped_lock (C++17) when you need to lock multiple mutexes atomically.\n\n---\n\n<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.