C++ Reference ยท Concurrency
C++ std::mutex class
Reference for std::mutex and its relatives: lock, try_lock, unlock, recursive_mutex and timed_mutex, with examples of protecting shared data from races.
std::mutex (header <mutex>) is the basic tool for mutual exclusion. A mutex is either locked by one thread or free. While a thread holds it, every other thread that calls lock() blocks until the owner calls unlock(). Code between the two calls is a critical section: only one thread at a time runs it, so shared data touched there cannot suffer a data race.
You rarely call lock() and unlock() yourself. If the code between them throws or returns early, the mutex stays locked forever. Wrap the mutex in a RAII lock such as std::lock_guard instead, and keep the mutex next to the data it protects.
std::mutex m; int counter = 0; void add() { std::lock_guard<std::mutex> guard(m); // locks here, unlocks at scope end ++counter; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
class mutex { public: constexpr mutex() noexcept; mutex(const mutex&) = delete; mutex& operator=(const mutex&) = delete; void lock(); bool try_lock(); void unlock(); native_handle_type native_handle(); };
| Name | Description |
|---|---|
lock() |
Blocks until the calling thread owns the mutex. |
try_lock() |
Takes the mutex if it is free and returns true; otherwise returns false immediately. It is allowed to fail spuriously, so do not treat false as proof that another thread holds it. |
unlock() |
Releases the mutex. The calling thread must own it. |
Returns: lock() and unlock() return nothing; try_lock() returns bool.
Errors / undefined behavior: locking a plain std::mutex you already own is undefined behavior (usually a deadlock). Calling unlock() on a mutex you do not own is undefined. Destroying a locked mutex, or one that threads are still waiting on, is undefined. lock() can throw std::system_error if the platform fails.
The mutex family
| Type | Header | Extra ability |
|---|---|---|
std::mutex |
<mutex> |
The basic non-recursive mutex. |
std::recursive_mutex |
<mutex> |
The owner may lock it repeatedly; it must unlock the same number of times. |
std::timed_mutex |
<mutex> |
Adds try_lock_for and try_lock_until. |
std::recursive_timed_mutex |
<mutex> |
Both of the above. |
std::shared_mutex |
<shared_mutex> |
Many readers or one writer (C++17). |
std::shared_timed_mutex |
<shared_mutex> |
Reader-writer lock with timeouts (C++14). |
Usage notes
- Mutexes are not copyable or movable. Store one as a member next to the data it guards. A class that contains a mutex is not copyable unless you write the copy operations yourself (and lock in them).
- Prefer RAII locks.
lock_guard,unique_lockandscoped_lockunlock on every exit path, including exceptions. - Lock several mutexes at once with
std::scoped_lock(orstd::lock), which avoids deadlock by using a deadlock-avoidance algorithm. Lockingathenbin one thread andbthenain another can deadlock. - Keep critical sections short. Never call unknown code (callbacks, virtual functions) or do I/O while holding a lock if you can avoid it.
- A mutex protects an invariant, not a variable. If two variables must change together, one mutex must cover both.
- A recursive mutex is usually a design smell. It hides the fact that a function that already holds the lock calls another function that locks again. Split the code into a locking public function and a non-locking private helper instead.
constmember functions often needmutable std::mutexso that they can lock.- Cost: an uncontended lock is cheap (a few atomic operations); a contended one makes threads sleep and wake, which costs microseconds.
- Memory ordering:
unlock()synchronizes with the nextlock(), so everything written before an unlock is visible after the next lock.