std::scoped_lock
std::scoped_lock (C++17) locks zero or more mutexes for a scope and unlocks them in the destructor. With two or more mutexes it uses a deadlock-avoiding lock algorithm, so you do not have to pick a manual lock order.
Detailed Explanation
Deadlock classic: thread A locks mu1 then mu2; thread B locks mu2 then mu1. Each holds one and waits for the other. The fix is a global order (always mu1 then mu2) or a single call that locks both atomically with respect to deadlock: std::lock(mu1, mu2).
scoped_lock is RAII over that idea. std::scoped_lock lock(mu1, mu2, mu3); locks all three, using std::lock internally when there are two or more, and unlocks all in reverse on destruction. One mutex is the same as lock_guard. Zero mutexes is a no-op, useful in generic code.
It is not movable and has no unlock. It is the "I need these mutexes for this whole block" type. If you need to wait on a condition variable, you still need a unique_lock on the mutex the cv is attached to; scoped_lock cannot unlock for wait.
std::lock plus adopt_lock guards is the C++11 spelling:
std::lock(mu1, mu2);
std::lock_guard<std::mutex> a(mu1, std::adopt_lock);
std::lock_guard<std::mutex> b(mu2, std::adopt_lock);
scoped_lock is one line and harder to get wrong.
It does not prevent deadlocks involving other mutexes you lock later inside the block. It does not prevent deadlocks if you nest scoped_lock(mu2, mu1) in a function that already holds one of them with a non-recursive mutex. Avoid nested locking; if you must, use one scoped_lock at the top with the full set.
Variadic templates mean the mutex types can differ (mutex and recursive_mutex together). All of them must provide lock/unlock in the std::lock sense.
Prefer documenting a lock hierarchy when the set of mutexes is large and stable. Prefer scoped_lock when a function needs two or three independent locks for one operation (transfer between two accounts).
Code Examples
#include <iostream>
#include <mutex>
#include <thread>
std::mutex a;
std::mutex b;
int x = 0;
int y = 0;
void transfer() {
std::scoped_lock lock(a, b); // deadlock-safe regardless of order
++x;
++y;
}
int main() {
std::thread t1(transfer);
std::thread t2(transfer);
t1.join();
t2.join();
std::cout << x + y << '\n'; // prints: 4
}#include <mutex>
std::mutex mu;
void one() {
std::scoped_lock lock(mu); // same as lock_guard for one mutex
}Common Gotchas
Already holding one of the mutexes
`scoped_lock(mu1, mu2)` while you own `mu1` on a non-recursive mutex deadlocks. Unlock first, or lock the full set once.
Unnamed temporary
`std::scoped_lock(mu1, mu2);` unlocks at the semicolon. Name the variable.