-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdeadlock.cpp
More file actions
44 lines (34 loc) · 755 Bytes
/
deadlock.cpp
File metadata and controls
44 lines (34 loc) · 755 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Description: Deadlock occurs when two threads are waiting each other to release resources.
*
* Cause: If two thread acquire mutexes in different order, they cause deadlock.
*
* Solution1: Acquire mutexes in same order.
*
* */
#include <thread>
#include <iostream>
#include <mutex>
#include <chrono>
using namespace std;
mutex mu1, mu2;
void some_op() {
mu1.lock();
mu2.lock();
// Do some work
this_thread::sleep_for(chrono::milliseconds(rand() % 100));
mu1.unlock();
mu2.unlock();
}
void some_other_op() {
mu2.lock();
mu1.lock();
// Do some work
this_thread::sleep_for(chrono::milliseconds(rand() % 100));
// This order is irrelevant to the deadlock
mu1.unlock();
mu2.unlock();
}
int main() {
return 0;
}