On this page
std::mutex & std::scoped_lock
Prev: std::jthread | Up: concurrency | Next: std::thread
Rel: RAII & Destructors, std::atomic
Ref: cppreference — std::scoped_lock
Tags: #public #prog #cpp #stdlib #concurrency #tier/core
Overview
std::mutex (<mutex>) provides mutual exclusion for shared state. Never call .lock()/.unlock() manually—always wrap mutexes in RAII lock guards:
std::scoped_lock(C++17, default choice): Locks one or multiple mutexes atomically using a deadlock-avoidance algorithm and unlocks on scope exit.std::unique_lock: Use when you need deferred locking, manual unlock before scope exit, orstd::condition_variable::wait(...).
Notes & Pitfalls
- Never call
.lock()/.unlock()manually: Always usestd::scoped_lock(C++17, deadlock-free for multiple mutexes) orstd::unique_lock(when pairing withstd::condition_variable).
Example
#include <cassert>
#include <mutex>
int main() {
std::mutex m;
int shared = 0;
{
std::scoped_lock lock(m);
shared += 42;
} // automatically unlocked
assert(shared == 42);
}
Linked from
Related notes
- tuts/cpp/stdlib/concurrency/atomic Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/jthread Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/thread Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib
- tuts/cpp/tutorials/jthread_work_queue_and_atomics links to this page; shared tags: #concurrency, #cpp, #prog, #tier
- tuts/cpp/builtins/raii_and_destructors Linked here; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/find_if shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/sort shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/transform shared tags: #cpp, #prog, #stdlib, #tier