std::mutex
std::mutex is a mutual-exclusion lock. Only one thread can own it at a time. You lock it before touching shared data and unlock it after. Lock it with std::lock_guard or std::unique_lock, not with bare lock()/unlock() in application code.
Detailed Explanation
Two threads increment counter++ and you lose updates. The increment is not atomic: read, add, write. A mutex makes the whole increment a critical section: the second thread waits until the first unlocks.
m.lock() blocks until the caller owns the mutex. m.unlock() releases it. try_lock() returns whether it acquired without waiting. Calling unlock if you do not own the mutex is undefined behaviour. Calling lock if you already own a non-recursive mutex is undefined behaviour (deadlock or worse). std::recursive_mutex allows the same thread to lock again; prefer to restructure rather than recurse through locks.
Never call lock/unlock yourself in production paths. An exception between them skips unlock and every other thread waits forever. std::lock_guard<std::mutex> lock(m); locks in the constructor and unlocks in the destructor, including on throw. That is RAII. unique_lock is the same idea with unlock-and-relock. scoped_lock locks several mutexes without a deadlock handshake you write yourself.
A mutex protects data, not code. Document which mutex guards which fields. One mutex per independent structure. One big mutex for the whole program serialises everything and is still better than a data race.
Mutexes are not recursive by default, not fair (a waiter can starve), and not async-signal-safe. Do not lock a mutex in a signal handler. Do not hold a mutex across a blocking network call if other threads need it; copy the data out, unlock, then send.
std::shared_mutex (C++17) allows many readers or one writer. Use it when reads dominate and the critical section is large enough to matter. For an int, an atomic is cheaper.
Static initialisation of a mutex is fine. A mutex as a member should live as long as the data it guards. Destroying a mutex that is still locked is undefined behaviour.
Code Examples
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
int counter = 0;
std::mutex mu;
void bump() {
std::lock_guard<std::mutex> lock(mu);
++counter;
}
int main() {
std::vector<std::thread> ts;
for (int i = 0; i < 8; ++i) ts.emplace_back(bump);
for (auto& t : ts) t.join();
std::cout << counter << '\n'; // prints: 8
}#include <mutex>
#include <string>
class Registry {
mutable std::mutex mu_;
std::string name_;
public:
void set(std::string n) {
std::lock_guard<std::mutex> lock(mu_);
name_ = std::move(n);
}
std::string get() const {
std::lock_guard<std::mutex> lock(mu_);
return name_;
}
};Common Gotchas
Lock/unlock by hand
a `throw` between them deadlocks the rest of the program. Use `lock_guard`.
Double-lock of a non-recursive mutex on the same thread
undefined. If `foo` locks and calls `bar` which locks the same mutex, you have a self-deadlock.
Holding a mutex while calling unknown code
that code may lock another mutex (deadlock) or take a long time (convoy). Copy, unlock, then call out.
`mutable` mutex on a const method
locking does not mutate the guarded data's meaning; it mutates the mutex. That is the valid use of `mutable`.