-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDetection.cpp
82 lines (70 loc) · 1.89 KB
/
Detection.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
using namespace std;
#define PN 5 // Processes Number
#define RN 3 // Resources Number
int p, r; // For Iterations
// Allocation Table
int allocation[PN][RN] = {
{0, 1, 0},
{2, 0, 0},
{3, 0, 3},
{2, 1, 1},
{0, 0, 2}};
// Request Table
int request[PN][RN] = {
{0, 0, 0},
{2, 0, 2},
{0, 0, 0},
{1, 0, 0},
{0, 0, 2}};
// Current Available Numbers Of Each Resource
int available[RN] = {0, 0, 0};
int *detectDeadlocks()
{
// Temporary Copy Of: 'available[RN]'
int tempAvail[RN];
for (r = 0; r < RN; r++)
tempAvail[r] = available[r];
// Array To Mark The Finished Processes With '1'
int *finished = new int[PN];
for (p = 0; p < PN; p++)
finished[p] = 0;
bool hasChanged = false;
do
{
hasChanged = false;
// Loop Through Processes
for (p = 0; p < PN; p++)
// If The Proccess Not Executed Before
if (finished[p] == 0)
{
// Check: Is This Process Request Resources More Than The Available?
for (r = 0; r < RN; r++)
if (request[p][r] > tempAvail[r])
break;
// If It Hasn't
if (r == RN)
{
finished[p] = 1;
cout << "\nP" << p << "\t";
for (r = 0; r < RN; r++)
{
tempAvail[r] += allocation[p][r];
cout << tempAvail[r] << "\t";
}
hasChanged = true;
}
}
} while (hasChanged);
return finished;
}
int main(int argc, char const *argv[])
{
int *deadlocks = detectDeadlocks();
cout << "\nDeadlocks At: ";
for (p = 0; p < PN; p++)
if (deadlocks[p] == 0)
cout << "P" << p << "\t";
getchar();
return 0;
}