-
Notifications
You must be signed in to change notification settings - Fork 1
/
Banker.cpp
126 lines (107 loc) · 2.8 KB
/
Banker.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#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, 2, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}};
// Maximum Table
int maximum[PN][RN] = {
{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}};
// Current Available Numbers Of Each Resource
int available[RN] = {3, 2, 2};
// Need Table
int need[PN][RN];
void calcNeed()
{
for (p = 0; p < PN; p++)
for (r = 0; r < RN; r++)
need[p][r] = maximum[p][r] - allocation[p][r];
}
bool isSystemSafe()
{
// Calculate Need Table
calcNeed();
// 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[PN] = {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 Need Resources More Than The Available?
for (r = 0; r < RN; r++)
if (need[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);
// Check: Is There A Process That Not Executed?
for (p = 0; p < PN; p++)
if (finished[p] == 0)
{
cout << "\nSystem Is UnSafe\n";
return false;
}
cout << "\nSystem Is Safe\n";
return true;
}
bool allocateIfSafe(int processNo, int request[RN])
{
// Change Tables Values
for (r = 0; r < RN; r++)
{
allocation[processNo][r] += request[r];
need[processNo][r] -= request[r];
available[r] -= request[r];
}
if (isSystemSafe())
return true;
// Restore Tables Values
for (r = 0; r < RN; r++)
{
allocation[processNo][r] -= request[r];
need[processNo][r] += request[r];
available[r] += request[r];
}
return false;
}
int main(int argc, char const *argv[])
{
// The Number Of Requested Resources
int request[RN] = {1, 0, 2};
if (allocateIfSafe(1, request))
cout << "The Request Is Accepted\n";
else
cout << "The Request Is Rejected\n";
getchar();
return 0;
}