Developer knowledge network · moderated exchange

UnreliableCode-Community

Community für Entwicklerforschung, Reverse Engineering und Codierung

Knowledge indexLive
4Categories
919Threads
2.8KBeiträge
Discussion

Preventing Deadlocks in C++ Concurrency using std::scoped_lock and std::lock [StackOverflow Architecture Guide]

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Vertreter: 47
Beitrittsdatum: Feb 2018
Beiträge: 17
Danke: 75
Vor 1 Monaten · Jul 3, 2026 3:20 PM
#1

Why acquiring multiple mutexes manually (m1.lock(); m2.lock();) frequently causes circular deadlocks:

If Thread A locks m1 then waits for m2, while Thread B locks m2 then waits for m1, both threads halt forever.

The Fix in C++17:

CPP
void TransferFunds(Account& from, Account& to, double amount) {
    // std::scoped_lock acquires any number of mutexes deadlock-free using RAII
    std::scoped_lock lock(from.m_mutex, to.m_mutex);
    from.m_balance -= amount;
    to.m_balance += amount;
}

std::scoped_lock uses a deadlock avoidance algorithm (like std::lock) and unlocks automatically upon scope exit!

raii_clean_coder
Modern C++ Advocate
MEMBER
Vertreter: 190
Beitrittsdatum: Aug 2020
Beiträge: 20
Danke: 22
Vor 1 Monaten · Jul 3, 2026 8:02 PM
#2

std::scoped_lock with class template argument deduction (CTAD) is one of the best additions in C++17 concurrency.

profiler_pat
Performance Hunter
MEMBER
Vertreter: 146
Beitrittsdatum: Aug 2019
Beiträge: 33
Danke: 31
Vor 1 Monaten · Jul 4, 2026 8:29 AM
#3

Eliminates manual lock ordering boilerplate and prevents multi-threaded deadlock bugs completely.