fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. const int P = 5; // Number of processes
  5. const int R = 3; // Number of resources
  6.  
  7. // Function to find the safe sequence
  8. void findSafeSequence(int processes[], int available[], int max[][R], int allot[][R]) {
  9. int need[P][R];
  10.  
  11. // Calculate need matrix
  12. for (int i = 0; i < P; i++)
  13. for (int j = 0; j < R; j++)
  14. need[i][j] = max[i][j] - allot[i][j];
  15.  
  16. bool finish[P] = {false};
  17. int safeSeq[P];
  18. int work[R];
  19.  
  20. for (int i = 0; i < R; i++)
  21. work[i] = available[i];
  22.  
  23. int count = 0;
  24. while (count < P) {
  25. bool found = false;
  26. for (int p = 0; p < P; p++) {
  27. if (!finish[p]) {
  28. bool canRun = true;
  29. for (int j = 0; j < R; j++) {
  30. if (need[p][j] > work[j]) {
  31. canRun = false;
  32. break;
  33. }
  34. }
  35.  
  36. if (canRun) {
  37. for (int k = 0; k < R; k++)
  38. work[k] += allot[p][k];
  39.  
  40. safeSeq[count++] = p;
  41. finish[p] = true;
  42. found = true;
  43. }
  44. }
  45. }
  46.  
  47. if (!found) {
  48. cout << "System is in an unsafe state. No safe sequence exists.\n";
  49. return;
  50. }
  51. }
  52.  
  53. cout << "System is in a safe state.\nSafe sequence is: ";
  54. for (int i = 0; i < P; i++)
  55. cout << "P" << safeSeq[i] << " ";
  56. cout << endl;
  57. }
  58.  
  59. int main() {
  60. int processes[] = {0, 1, 2, 3, 4};
  61.  
  62. int available[R] = {3, 3, 2};
  63.  
  64. int max[P][R] = {
  65. {7, 5, 3},
  66. {3, 2, 2},
  67. {9, 0, 2},
  68. {2, 2, 2},
  69. {4, 3, 3}
  70. };
  71.  
  72. int allot[P][R] = {
  73. {0, 1, 0},
  74. {2, 0, 0},
  75. {3, 0, 2},
  76. {2, 1, 1},
  77. {0, 0, 2}
  78. };
  79.  
  80. findSafeSequence(processes, available, max, allot);
  81. return 0;
  82. }
  83.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
System is in a safe state.
Safe sequence is: P1 P3 P4 P0 P2