What conditions produce deadlock, and how do lock ordering and std::scoped_lock help prevent it?
Show answer and explanation
Deadlock is possible when mutual exclusion, hold-and-wait, no preemption, and circular wait all hold, such as two threads acquiring the same pair of mutexes in opposite orders. A global lock order removes circular wait, while std::scoped_lock uses a deadlock-avoidance algorithm to acquire multiple mutexes and releases them through RAII. Good designs also keep critical sections small, avoid calling unknown code while holding locks, document lock hierarchy, and treat timeout or try-lock loops as recovery policies rather than proof that shared-state logic is correct.
Deadlock is possible when mutual exclusion, hold-and-wait, no preemption, and circular wait all hold, such as two threads acquiring the same pair of mutexes in opposite orders. A global lock order removes circular wait, while std::scoped_lock uses a deadlock-avoidance algorithm to acquire multiple mutexes and releases them through RAII. Good designs also keep critical sections small, avoid calling unknown code while holding locks, document lock hierarchy, and treat timeout or try-lock loops as recovery policies rather than proof that shared-state logic is correct.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.