Deadlock Prevention

Avoiding and detecting deadlocks

Interview Relevant: Common concurrency issue

Deadlock Prevention

Strategies to avoid deadlock conditions.

Code Examples

Deadlock prevention strategies.

cpp
1// Deadlock conditions:
2// 1. Mutual exclusion
3// 2. Hold and wait
4// 3. No preemption
5// 4. Circular wait
6
7// Deadlock example
8mutex m1, m2;
9
10void thread1() {
11    lock_guard<mutex> l1(m1);
12    this_thread::sleep_for(chrono::milliseconds(1));
13    lock_guard<mutex> l2(m2);  // Waits for m2
14}
15
16void thread2() {
17    lock_guard<mutex> l2(m2);
18    this_thread::sleep_for(chrono::milliseconds(1));
19    lock_guard<mutex> l1(m1);  // Waits for m1
20}  // Deadlock!
21
22// Prevention 1: Lock ordering (always lock in same order)
23void safe1() {
24    lock_guard<mutex> l1(m1);
25    lock_guard<mutex> l2(m2);
26}
27
28// Prevention 2: Lock both at once
29void safe2() {
30    scoped_lock lock(m1, m2);  // C++17
31}
32
33// Prevention 3: Try lock with timeout
34void safe3() {
35    unique_lock<mutex> l1(m1, defer_lock);
36    unique_lock<mutex> l2(m2, defer_lock);
37    lock(l1, l2);  // Lock both or none
38}
39
40// Prevention 4: Hierarchical locking
41class HierarchicalMutex {
42    mutex mtx;
43    int level;
44    static thread_local int currentLevel;
45    // Only lock if level < currentLevel
46};

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In