Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

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 months ago · 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 months ago · 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 months ago · Jul 4, 2026 8:29 AM
#3

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