fork download
  1. #include <stdio.h>
  2.  
  3. int main() {
  4. int numProcesses = 5; // Number of processes
  5. int numResources = 3; // Number of resources
  6.  
  7. int allocationMatrix[5][3] = {{0, 1, 0}, {2, 0, 0}, {3, 0, 2}, {2, 1, 1}, {0, 0, 2}}; // Allocation Matrix
  8. int maxMatrix[5][3] = {{7, 5, 3}, {3, 2, 2}, {9, 0, 2}, {2, 2, 2}, {4, 3, 3}}; // MAX Matrix
  9. int availableResources[3] = {3, 3, 2}; // Available Resources
  10.  
  11. int isFinished[numProcesses], safeSequence[numProcesses], index = 0;
  12. for (int k = 0; k < numProcesses; k++) {
  13. isFinished[k] = 0;
  14. }
  15.  
  16. int needMatrix[numProcesses][numResources];
  17. for (int i = 0; i < numProcesses; i++) {
  18. for (int j = 0; j < numResources; j++)
  19. needMatrix[i][j] = maxMatrix[i][j] - allocationMatrix[i][j];
  20. }
  21.  
  22. for (int k = 0; k < numProcesses; k++) {
  23. for (int i = 0; i < numProcesses; i++) {
  24. if (isFinished[i] == 0) {
  25. int flag = 0;
  26. for (int j = 0; j < numResources; j++) {
  27. if (needMatrix[i][j] > availableResources[j]) {
  28. flag = 1;
  29. break;
  30. }
  31. }
  32. if (flag == 0) {
  33. safeSequence[index++] = i;
  34. for (int y = 0; y < numResources; y++)
  35. availableResources[y] += allocationMatrix[i][y];
  36. isFinished[i] = 1;
  37. }
  38. }
  39. }
  40. }
  41.  
  42. int flag = 1;
  43. for (int i = 0; i < numProcesses; i++) {
  44. if (isFinished[i] == 0) {
  45. flag = 0;
  46. printf("The system is not safe.\n");
  47. break;
  48. }
  49. }
  50.  
  51. if (flag == 1) {
  52. printf("SAFE Sequence: ");
  53. for (int i = 0; i < numProcesses - 1; i++)
  54. printf("P%d -> ", safeSequence[i]);
  55. printf("P%d\n", safeSequence[numProcesses - 1]);
  56. }
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0.01s 5288KB
stdin
45
stdout
SAFE Sequence: P1 -> P3 -> P4 -> P0 -> P2