Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Discussion

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

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Өкіл: 47
Қосылу күні: Feb 2018
Хабарламалар: 17
Рахмет: 75
1 ай бұрын · 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
Өкіл: 190
Қосылу күні: Aug 2020
Хабарламалар: 20
Рахмет: 22
1 ай бұрын · 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
Өкіл: 146
Қосылу күні: Aug 2019
Хабарламалар: 33
Рахмет: 31
1 ай бұрын · Jul 4, 2026 8:29 AM
#3

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