Use std::mutex and std::lock_guard in C++
Guard shared state in C++20 with std::mutex and std::lock_guard so the lock is released on every path, even exceptions. Includes unique_lock.

C needs you to remember to unlock. C++ lets the compiler remember for you. std::mutex provides lock and unlock, and std::lock_guard is a small object that locks in its constructor and unlocks in its destructor, so the mutex is released when the scope ends no matter how it ends: a normal return, an early return, or an exception. This post shows the pattern with GCC 14 compiling C++20, builds a small thread-safe class, and explains when to reach for std::unique_lock instead. It assumes you have seen why shared data needs a mutex, as covered in the post on race conditions in this cluster.
The problem with manual locking in C++
Here is the C-style approach written in C++.
#include <mutex>
#include <vector>
#include <stdexcept>
std::mutex m;
std::vector<int> data;
void add_checked(int v) {
m.lock();
if (v < 0)
throw std::invalid_argument("negative");
data.push_back(v);
m.unlock();
}When v is negative, the function throws while holding m. The unlock never runs. The mutex stays locked forever, and the next thread to call add_checked blocks permanently. Even without exceptions, push_back can throw std::bad_alloc, so any code between lock and unlock that can throw is a leak risk. Manual lock and unlock pairs are fragile in C++, and the standard library discourages them.
std::lock_guard
std::lock_guard<std::mutex> is declared in <mutex>. Its constructor locks the mutex and its destructor unlocks it. This is RAII, resource acquisition is initialization: the lifetime of the object is the lifetime of the lock.
#include <mutex>
#include <vector>
#include <stdexcept>
#include <thread>
#include <iostream>
std::mutex m;
std::vector<int> data;
void add_checked(int v) {
std::lock_guard<std::mutex> g(m);
if (v < 0)
throw std::invalid_argument("negative");
data.push_back(v);
}
int main() {
std::thread t1([] { for (int i = 0; i < 1000; i++) add_checked(i); });
std::thread t2([] { for (int i = 0; i < 1000; i++) add_checked(i); });
t1.join();
t2.join();
try {
add_checked(-1);
} catch (const std::invalid_argument &e) {
std::cout << "caught: " << e.what() << "\n";
}
add_checked(7);
std::cout << "size = " << data.size() << "\n";
}Compile with g++ -std=c++20 -O2 -pthread guard.cpp -o guard.
caught: negative
size = 2001The throw leaves add_checked, the destructor of g runs during stack unwinding, and the mutex is unlocked. The later call to add_checked(7) works. The vector holds 2,000 values from the threads plus the final 7, which is why the size is 2001. With manual locking the last call would have deadlocked.
Since C++17 you can omit the template argument thanks to class template argument deduction, so std::lock_guard g(m); works. Writing it out is also common and equally valid.
Name the guard, scope the lock
Two small traps catch beginners. The first is forgetting to name the object.
void bad() {
std::lock_guard<std::mutex>(m); // declares a variable named m, does not compile
// ...
}The parentheses make this a declaration of a variable named m of type lock_guard, not a temporary that locks the global mutex. Because lock_guard has no default constructor the compiler rejects it, but the same slip with a type that does have one, such as std::unique_lock, compiles and locks nothing. Always give the guard a name, as in std::lock_guard<std::mutex> g(m);.
The second is making the lock live longer than it needs to. The guard unlocks at the closing brace of its scope, so use a block to end the critical section early.
void process(int v) {
int prepared = v * 2; // no shared state, no lock
{
std::lock_guard<std::mutex> g(m);
data.push_back(prepared); // critical section
} // unlocked here
expensive_log(prepared); // runs without the lock
}A thread-safe class
Keep the mutex as a private member next to the data, and take the guard in each public method. Declare the mutex mutable if you need to lock inside const methods, because locking changes the mutex's state, not the object's logical value.
#include <mutex>
#include <iostream>
#include <thread>
class Account {
public:
void deposit(long cents) {
std::lock_guard<std::mutex> g(m_);
balance_ += cents;
}
bool withdraw(long cents) {
std::lock_guard<std::mutex> g(m_);
if (balance_ < cents)
return false;
balance_ -= cents;
return true;
}
long balance() const {
std::lock_guard<std::mutex> g(m_);
return balance_;
}
private:
mutable std::mutex m_;
long balance_ = 0;
};
int main() {
Account acct;
auto work = [&acct] {
for (int i = 0; i < 100000; i++)
acct.deposit(1);
};
std::thread a(work), b(work);
a.join();
b.join();
std::cout << "balance = " << acct.balance() << "\n";
}balance = 200000Notice that withdraw checks the balance and subtracts it under one lock. Splitting that into a public balance() call followed by a separate subtract would let another thread change the balance in between. Make the check and the update one critical section. This is the main design rule for thread-safe classes: expose operations, not getters and setters that callers combine.
When you need std::unique_lock
std::lock_guard is deliberately minimal. It cannot be unlocked early, moved or reused. std::unique_lock adds those. It also is the type that std::condition_variable::wait requires, because a wait must release the mutex and reacquire it.
#include <mutex>
#include <queue>
std::mutex m;
std::queue<int> q;
bool try_take(int &out) {
std::unique_lock<std::mutex> lk(m);
if (q.empty())
return false;
out = q.front();
q.pop();
lk.unlock(); // release early; the destructor will not unlock again
return true;
}unique_lock tracks whether it owns the lock, so unlocking early and then letting the destructor run is safe. It has a small size and run-time cost over lock_guard, because it stores that ownership flag. Use lock_guard by default and unique_lock when you need to unlock, defer locking, or wait on a condition variable. For C++17 and later, std::scoped_lock is a lock_guard that can lock several mutexes at once without deadlock, which the next post in this cluster covers.
Not recursive by default
std::mutex is not recursive. If a thread that already holds it locks it again, the behavior is undefined: in practice a deadlock on glibc, and the C++ standard says a mutex ownership violation is not specified. A public method that locks and calls another public method that also locks will hang. Either factor out a private unlocked helper that both call, or restructure so the lock is taken at one level. std::recursive_mutex exists but usually hides a design problem.
Where this stops
A std::mutex protects what you put behind it and nothing else. It does not protect data the compiler lets you leak out: returning a reference to a member from a locked method hands the caller unguarded access. Keep references to protected data inside the locked scope, or return copies. Nor does it help with waiting for something to become true. For that, use a condition variable.
Check the result under ThreadSanitizer
The examples above give the right output, and that alone proves little for concurrent code. Build the class with g++ -std=c++20 -g -O1 -fsanitize=thread -pthread account.cpp -o account_tsan and run it. A correct program prints the balance and no warning. If you remove the guard from balance(), the tool prints a warning that starts with WARNING: ThreadSanitizer: data race, naming the read in balance() and the write in deposit() that raced with it. Reads need the lock as much as writes do, and this is the quickest way to prove it to yourself.
The GCC and Clang manuals both document -fsanitize=thread. It slows the program and increases its memory use noticeably, so use it in a test build, not in production. It also cannot see a race that does not occur during the run, so a clean report is evidence, not proof.
Pairing the guard with data
One more idiom is worth adopting early. Wrap the mutex and the data it protects in one small class so the compiler enforces the pairing, and give the data no public accessor except one that takes a callable.
#include <mutex>
#include <utility>
#include <vector>
#include <iostream>
template <typename T>
class Guarded {
public:
template <typename F>
auto with(F &&f) {
std::lock_guard<std::mutex> g(m_);
return std::forward<F>(f)(value_);
}
private:
std::mutex m_;
T value_{};
};
int main() {
Guarded<std::vector<int>> v;
v.with([](std::vector<int> &x) { x.push_back(42); });
auto n = v.with([](std::vector<int> &x) { return x.size(); });
std::cout << "size = " << n << "\n";
}size = 1Callers can no longer touch the vector without the lock, because the only door is with. The one remaining hazard is a callable that stores the reference it receives somewhere that outlives the call, so treat the reference as valid only inside the callable.


