How to Use lock_guard in C++ for Safe Mutex Locking
Use
std::lock_guard in C++ to automatically lock a mutex when the guard is created and unlock it when the guard goes out of scope. This ensures safe and exception-proof locking without manual unlock calls.Syntax
The basic syntax for std::lock_guard is:
std::lock_guard<std::mutex> guard(mutex);Here, mutex is the std::mutex object you want to lock. The lock_guard locks the mutex immediately upon creation and unlocks it automatically when it is destroyed (usually at the end of the scope).
cpp
std::mutex mtx;
{
std::lock_guard<std::mutex> guard(mtx);
// critical section code here
} // mtx is unlocked automatically hereExample
This example shows how std::lock_guard protects a shared counter from race conditions by locking a mutex during increment operations.
cpp
#include <iostream> #include <thread> #include <mutex> std::mutex mtx; int counter = 0; void increment() { for (int i = 0; i < 1000; ++i) { std::lock_guard<std::mutex> guard(mtx); ++counter; // safe increment } } int main() { std::thread t1(increment); std::thread t2(increment); t1.join(); t2.join(); std::cout << "Counter: " << counter << std::endl; return 0; }
Output
Counter: 2000
Common Pitfalls
Common mistakes when using std::lock_guard include:
- Trying to unlock the mutex manually (not needed and not allowed).
- Creating the
lock_guardwithout a mutex reference or with a temporary mutex. - Using
lock_guardwhen you need to lock and unlock multiple times (usestd::unique_lockinstead).
Always let lock_guard manage the lock lifetime automatically.
cpp
/* Wrong way: manual unlock (won't compile) */ // std::mutex mtx; // std::lock_guard<std::mutex> guard(mtx); // guard.unlock(); // error: no unlock() method /* Right way: automatic unlock */ std::mutex mtx; { std::lock_guard<std::mutex> guard(mtx); // critical section } // mutex unlocked here automatically
Quick Reference
std::lock_guard<MutexType> is a simple RAII wrapper for mutex locking.
- Locks mutex on creation.
- Unlocks mutex on destruction.
- No manual unlock method.
- Use for simple scoped locking.
Key Takeaways
Use std::lock_guard to automatically lock and unlock a mutex within a scope.
Do not manually unlock a mutex managed by lock_guard; it unlocks automatically.
lock_guard is best for simple, scoped locking without manual control.
For more flexible locking (lock/unlock multiple times), use std::unique_lock instead.
Always pass a valid mutex reference to lock_guard to avoid errors.