1+ #include < iostream>
2+ using namespace std ;
3+
4+ const int P = 5 ;
5+
6+ const int R = 3 ;
7+
8+ void calculateNeed (int need[P][R], int maxm[P][R],
9+ int allot[P][R])
10+ {
11+ for (int i = 0 ; i < P ; i++)
12+ for (int j = 0 ; j < R ; j++)
13+ need[i][j] = maxm[i][j] - allot[i][j];
14+ }
15+
16+ bool isSafe (int processes[], int avail[], int maxm[][R],
17+ int allot[][R])
18+ {
19+ int need[P][R];
20+ calculateNeed (need, maxm, allot);
21+ bool finish[P] = {0 };
22+ int safeSeq[P];
23+ int work[R];
24+ for (int i = 0 ; i < R ; i++)
25+ work[i] = avail[i];
26+
27+ int count = 0 ;
28+ while (count < P)
29+ {
30+ bool found = false ;
31+ for (int p = 0 ; p < P; p++)
32+ {
33+ if (finish[p] == 0 )
34+ {
35+ int j;
36+ for (j = 0 ; j < R; j++)
37+ if (need[p][j] > work[j])
38+ break ;
39+ if (j == R)
40+ {
41+ for (int k = 0 ; k < R ; k++)
42+ work[k] += allot[p][k];
43+ safeSeq[count++] = p;
44+ finish[p] = 1 ;
45+ found = true ;
46+ }
47+ }
48+ }
49+ if (found == false )
50+ {
51+ cout << " System is not in safe state" ;
52+ return false ;
53+ }
54+ }
55+ cout << " System is in safe state.\n Safe"
56+ " sequence is: " ;
57+ for (int i = 0 ; i < P ; i++)
58+ cout << safeSeq[i] << " " ;
59+
60+ return true ;
61+ }
62+ int main ()
63+ {
64+ int processes[] = {0 , 1 , 2 , 3 , 4 };
65+
66+ int avail[] = {3 , 3 , 2 };
67+
68+ int maxm[][R] = {{7 , 5 , 3 },
69+ {3 , 2 , 2 },
70+ {9 , 0 , 2 },
71+ {2 , 2 , 2 },
72+ {4 , 3 , 3 }};
73+
74+ int allot[][R] = {{0 , 1 , 0 },
75+ {2 , 0 , 0 },
76+ {3 , 0 , 2 },
77+ {2 , 1 , 1 },
78+ {0 , 0 , 2 }};
79+
80+ isSafe (processes, avail, maxm, allot);
81+ return 0 ;
82+ }
0 commit comments