C++ Reference ยท Concurrency
C++ lock_guard, unique_lock and scoped_lock
Reference for the RAII lock wrappers lock_guard, unique_lock and scoped_lock: when to use each, deferred locking, try_to_lock, adopt_lock and deadlock avoidance.
The lock wrappers in <mutex> acquire a mutex in their constructor and release it in their destructor (RAII). Whatever way a scope ends (return, break, exception), the mutex is unlocked. There are three of them, from simplest to most flexible: std::lock_guard, std::scoped_lock (C++17) and std::unique_lock.
Use scoped_lock as your default: it works with one mutex or several. Reach for unique_lock when you need to unlock early, lock later, try with a timeout, move the lock around, or wait on a condition_variable.
std::mutex a, b; { std::scoped_lock both(a, b); // locks both, deadlock-free } std::unique_lock lk(a, std::defer_lock); lk.lock(); // lock now lk.unlock(); // and release early
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
template<class Mutex> class lock_guard { explicit lock_guard(Mutex& m); lock_guard(Mutex& m, std::adopt_lock_t); }; template<class... Mutexes> class scoped_lock { // C++17 explicit scoped_lock(Mutexes&... ms); scoped_lock(std::adopt_lock_t, Mutexes&... ms); }; template<class Mutex> class unique_lock { unique_lock() noexcept; explicit unique_lock(Mutex& m); unique_lock(Mutex& m, std::defer_lock_t) noexcept; unique_lock(Mutex& m, std::try_to_lock_t); unique_lock(Mutex& m, std::adopt_lock_t); unique_lock(Mutex& m, const std::chrono::duration<...>& timeout); unique_lock(Mutex& m, const std::chrono::time_point<...>& deadline); // lock(), try_lock(), try_lock_for(), try_lock_until(), unlock(), // owns_lock(), operator bool, mutex(), release(), swap() };
| Name | Description |
|---|---|
std::defer_lock |
Do not lock in the constructor; the object starts without ownership (unique_lock only). |
std::try_to_lock |
Call try_lock() in the constructor; check owns_lock() afterwards (unique_lock only). |
std::adopt_lock |
The calling thread already holds the mutex; the wrapper takes responsibility for unlocking. |
owns_lock() |
true if the unique_lock currently holds its mutex. |
release() |
Detaches the mutex without unlocking and returns a pointer to it. |
Returns: constructors build the lock object; owns_lock() returns bool.
Errors / undefined behavior: locking a non-recursive mutex the thread already owns is undefined. unique_lock::lock() throws std::system_error if it has no mutex or already owns it. Using adopt_lock on a mutex that is not locked by the current thread is undefined.
Comparison
| Feature | lock_guard |
scoped_lock |
unique_lock |
|---|---|---|---|
| Number of mutexes | 1 | 0 or more | 1 |
| Deadlock avoidance for several | no | yes | no (use std::lock) |
| Unlock early / relock | no | no | yes |
| Movable | no | no | yes |
Works with condition_variable |
no | no | yes |
| Overhead | none | none | one flag |
Usage notes
- Name the variable.
std::lock_guard<std::mutex>(m);without a name creates a temporary that unlocks immediately. Writestd::lock_guard<std::mutex> g(m);. - Class template argument deduction (C++17) lets you write
std::scoped_lock lk(a, b);andstd::unique_lock lk(m);without the template argument. - Deadlock avoidance:
scoped_lockwith several mutexes uses the same algorithm asstd::lock, so the order of arguments does not matter between threads. - Condition variables need
unique_lockbecausewait()has to unlock and relock the mutex. - Narrow the scope with an extra pair of braces if you only need the lock for part of a function.
scoped_lockwith zero mutexes is allowed and does nothing, which is handy in generic code.- Locks are not copyable.
unique_lockcan be moved, which lets a function return a held lock.
Related
- std::mutex
- std::shared_mutex (use
shared_lockfor readers) - std::condition_variable
- Tutorial: Mutexes and Locks