-
Notifications
You must be signed in to change notification settings - Fork 0
/
Deadlock Detection Using Cycle Method.cpp
111 lines (100 loc) · 2.23 KB
/
Deadlock Detection Using Cycle Method.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include<bits/stdc++.h>
#define WHITE 0
#define GRAY 1
#define BLACK 2
using namespace std;
int noOfNodes,noOfEdges;
vector<int >adj[15];
bool isFoundDeadlock = false;
int isMarked[15];
int L[20];
int Size = 0;
map < string ,int> node;
map <int , string > reveseNode;
stack < int > cycleElements;
void print()
{
cout << "cycles are : ";
while(!cycleElements.empty()){
cout << reveseNode[cycleElements.top()] << " ";
cycleElements.pop();
}
cout << endl;
isFoundDeadlock = true;
}
void Detection(int startingNode)
{
isMarked[startingNode] = GRAY;
L[Size++] = startingNode;
for(int i=0; i<adj[startingNode].size(); i++){
int v = adj[startingNode][i];
//cout << "adj : " << reveseNode[v] << endl;
if(isMarked[v] == WHITE){
Detection(v);
}else if(isMarked[v] == GRAY){
for(int j=Size-1; j>=0; j--){
if(v == L[j]){
cycleElements.push(v);
break;
}else{
cycleElements.push(L[j]);
Size--;
}
}
print();
}
}
isMarked[startingNode] = BLACK;
}
int main()
{
cout << "Enter number of nodes & Edges : ";
cin >> noOfNodes >> noOfEdges;
cout << "Nodes Name : ";
for(int i=0; i<noOfNodes; i++){
string name;
cin >> name;
node[name] = i;
reveseNode[i] = name;
isMarked[i] = WHITE;
}
for(int i=0; i<noOfEdges; i++){
string u,v;
cin >> u >> v;
//adj[u].push_back(v);
adj[node[u]].push_back(node[v]);
}
cout << "Enter staring Nodes : ";
string startingNode;
cin >> startingNode;
Detection(node[startingNode]);
for(int i=0; i<noOfNodes; i++){
if(isMarked[i] == WHITE){
Detection(i);
}
}
isFoundDeadlock ? cout << "Deadlock Found" << endl : cout << "No Deadlock Found" << endl;
return 0;
}
/**
Sample Input:
13 13
R A C S D T B E F U V W G
R A
A S
C S
D T
D S
F S
W F
U D
B T
T E
E V
V G
G U
R
Sample Output:
cycles are : D T E V G U
Deadlock Found
*/