std::lock_guard
std::lock_guard<Mutex> locks a mutex in its constructor and unlocks it in its destructor. It is the default RAII wrapper for a critical section that lasts exactly one scope.
Detailed Explanation
A mutex you lock with m.lock() must be unlocked on every path, including exceptions. lock_guard is a tiny object whose only job is that pair. You write std::lock_guard<std::mutex> lock(m); at the top of the block that touches the shared data. When the block ends, the guard unlocks, even if a string allocation threw.
The guard is not copyable or movable. It has no unlock. The mutex stays owned until the guard dies. If you need to unlock early, use unique_lock. If you need to lock two mutexes, use scoped_lock.
Construction can take std::adopt_lock: you already own the mutex (you called std::lock(m1, m2)), and the guard will unlock it. Construction cannot take defer_lock; that is unique_lock.
The type is a template so it works with std::mutex, recursive_mutex, timed_mutex, and any type that provides lock and unlock. It does not work with a mutex you must try_lock in a loop; again, unique_lock.
Name the variable. std::lock_guard<std::mutex>(m); is a temporary that unlocks at the end of the statement, which is the next semicolon. The critical section is empty. This is the most common lock_guard bug.
A guard in a loop body locks and unlocks every iteration. A guard outside the loop holds the mutex for the whole loop. Pick the smaller critical section that is still correct.
lock_guard is not a substitute for documenting what the mutex protects. It only guarantees unlock.
C++17 scoped_lock with one mutex is equivalent and can also take zero or many. Some style guides use scoped_lock for everything. lock_guard remains the clearest "I am locking this one mutex for this scope".
Code Examples
#include <mutex>
#include <string>
#include <vector>
std::mutex mu;
std::vector<std::string> log;
void record(std::string line) {
std::lock_guard<std::mutex> lock(mu);
log.push_back(std::move(line)); // unlocks if push_back throws
}
int main() {
record("boot");
}#include <iostream>
#include <mutex>
std::mutex mu;
int n = 0;
int main() {
{
std::lock_guard<std::mutex> lock(mu);
++n;
} // unlocked here
std::cout << n << '\n'; // prints: 1
}Common Gotchas
Unnamed temporary
`std::lock_guard<std::mutex>(mu);` unlocks immediately. Name it.
The guard must outlive the last use of the data
do not return a reference to a locked object after the guard is gone unless the caller is supposed to lock again.
No early unlock
if the second half of the function does not need the mutex, close the brace of an inner block so the guard dies, or switch to `unique_lock`.
Two `lock_guard`s on the same non-recursive mutex in one thread
deadlock. Use one guard, or a recursive mutex, or restructure.