-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeadlock_simulation.cpp
executable file
·67 lines (60 loc) · 1.91 KB
/
deadlock_simulation.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* @author Mostafa Talebi
* @email [email protected]
* @description This script simulates the problem of deadlock in concurrent programming,
* when two threads both try to acquire the lock of an object, both working on a different
* instances of the same object, and hence are waiting for the other to release the lock of
* an already owned lock.
**/
#include <iostream>
#include <thread>
#include <mutex>
class SampleObject
{
public:
std::mutex _mutex;
void print()
{
std::cout << "ID: #" << std::this_thread::get_id() << std::endl;
}
};
void set_operation(SampleObject &S1, SampleObject &S2)
{
std::cout << "Try to lock..." << std::endl;
std::unique_lock<std::mutex> l1(S1._mutex);
std::cout << "Locked successfully." << std::endl;
S1.print();
std::unique_lock<std::mutex> l2(S2._mutex);
S2.print();
}
void set_operation2(SampleObject &S1, SampleObject &S2)
{
std::cout << "Try to lock..." << std::endl;
std::unique_lock<std::mutex> l2(S2._mutex);
std::cout << "Locked successfully." << std::endl;
S1.print();
std::unique_lock<std::mutex> l1(S1._mutex);
S2.print();
}
int main() {
SampleObject S11;
SampleObject S22;
std::thread th(set_operation, std::ref(S11), std::ref(S22));
std::thread th2(set_operation2, std::ref(S11), std::ref(S22));
std::thread th3(set_operation, std::ref(S11), std::ref(S22));
std::thread th4(set_operation2, std::ref(S11), std::ref(S22));
std::thread th5(set_operation, std::ref(S11), std::ref(S22));
std::thread th6(set_operation2, std::ref(S11), std::ref(S22));
std::thread th7(set_operation, std::ref(S11), std::ref(S22));
std::thread th8(set_operation2, std::ref(S11), std::ref(S22));
// std::thread th2(set_operation, std::ref(S33), std::ref(S44));
th.join();
th2.join();
th3.join();
th4.join();
th5.join();
th6.join();
th7.join();
th8.join();
return 0;
}