-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.c
93 lines (88 loc) · 2.21 KB
/
code.c
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
//Code for Banker’s Algorithm
#include<iostream>
using namespace std;
// Number of processes
const int P = 5;
// Number of resources
const int R = 3;
// Function to find the need of each process
void calculateNeed(int need[P][R], int maxm[P][R],
int allot[P][R]) {
// Calculating Need of each P
for (int i = 0 ; i < P ; i++)
for (int j = 0 ; j < R ; j++)
// Need of instance = maxm instance -
//allocated instance
need[i][j] = maxm[i][j] - allot[i][j]; }
// Function to find the system is in safe state or not
bool isSafe(int processes[], int avail[], int maxm[][R],
int allot[][R]) {
int need[P][R];
// Function to calculate need matrix
calculateNeed(need, maxm, allot);
// Mark all processes as infinish
bool finish[P] = {0};
// To store safe sequence
int safeSeq[P];
// Make a copy of available resources
int work[R];
for (int i = 0; i < R ; i++)
work[i] = avail[i];
// While all processes are not finished
// or system is not in safe state.
int count = 0;
while (count < P) {
bool found = false;
for (int p = 0; p < P; p++) {
// First check if a process is finished,
// if no, go for next condition
if (finish[p] == 0) {
// Check if for all resources of
// current P need is less
// than work
int j;
for (j = 0; j < R; j++)
if (need[p][j] > work[j])
break;
// If all needs of p were satisfied.
if (j == R) {
for (int k = 0 ; k < R ; k++)
work[k] += allot[p][k];
// Add this process to safe sequence.
safeSeq[count++] = p;
// Mark this p as finished
finish[p] = 1;
found = true; } } }
if (found == false){
cout << "System is not in safe state";
return false; } }
// If system is in safe state then
// safe sequence will be as below
cout << "System is in safe state.\nSafe"
" sequence is: ";
for (int i = 0; i < P ; i++)
cout << safeSeq[i] << " ";
return true;}
// Driver code
int main() {
int processes[] = {0, 1, 2, 3, 4};
// Available instances of resources
int avail[] = {3, 3, 2};
// Maximum R that can be allocated
int maxm[][R] = {{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}};
// Resources allocated to processes
int allot[][R] = {{0, 1, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}};
// Check system is in safe state or not
isSafe(processes, avail, maxm, allot);
return 0;}
Output:
System is in safe state.
Safe sequence is: 1 3 4 0 2