fork download
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. #define MAX_PROCESSES 5
  5. #define MAX_RESOURCES 3
  6.  
  7. // Function to check if all processes can finish
  8. bool canFinish(int process, int finish[], int need[MAX_PROCESSES][MAX_RESOURCES], int work[], int m) {
  9. for (int i = 0; i < m; i++) {
  10. if (need[process][i] > work[i])
  11. return false;
  12. }
  13. return true;
  14. }
  15.  
  16. // Deadlock Detection Function
  17. bool detectDeadlock(int processes[], int available[], int max[MAX_PROCESSES][MAX_RESOURCES], int allocation[MAX_PROCESSES][MAX_RESOURCES], int need[MAX_PROCESSES][MAX_RESOURCES], int n, int m) {
  18. int work[MAX_RESOURCES];
  19. int finish[MAX_PROCESSES] = {0};
  20.  
  21. // Initialize work as available
  22. for (int i = 0; i < m; i++) {
  23. work[i] = available[i];
  24. }
  25.  
  26. bool deadlock = false;
  27.  
  28. for (int i = 0; i < n; i++) {
  29. if (!finish[i] && canFinish(i, finish, need, work, m)) {
  30. for (int j = 0; j < m; j++) {
  31. work[j] += allocation[i][j];
  32. }
  33. finish[i] = 1;
  34. i = -1; // Restart the process to check for others
  35. }
  36. }
  37.  
  38. for (int i = 0; i < n; i++) {
  39. if (!finish[i]) {
  40. deadlock = true;
  41. printf("Process %d is in deadlock\n", i);
  42. }
  43. }
  44.  
  45. return deadlock;
  46. }
  47.  
  48. int main() {
  49. int n = MAX_PROCESSES; // Number of processes
  50. int m = MAX_RESOURCES; // Number of resources
  51.  
  52. int processes[MAX_PROCESSES] = {0, 1, 2, 3, 4};
  53.  
  54. // Available instances of resources
  55. int available[MAX_RESOURCES] = {3, 3, 2};
  56.  
  57. // Maximum R that can be allocated to processes
  58. int max[MAX_PROCESSES][MAX_RESOURCES] = {
  59. {7, 5, 3},
  60. {3, 2, 2},
  61. {9, 0, 2},
  62. {2, 2, 2},
  63. {4, 3, 3}
  64. };
  65.  
  66. // Resources allocated to processes
  67. int allocation[MAX_PROCESSES][MAX_RESOURCES] = {
  68. {0, 1, 0},
  69. {2, 0, 0},
  70. {3, 0, 2},
  71. {2, 1, 1},
  72. {0, 0, 2}
  73. };
  74.  
  75. // Need of each process
  76. int need[MAX_PROCESSES][MAX_RESOURCES];
  77. for (int i = 0; i < n; i++) {
  78. for (int j = 0; j < m; j++) {
  79. need[i][j] = max[i][j] - allocation[i][j];
  80. }
  81. }
  82.  
  83. if (detectDeadlock(processes, available, max, allocation, need, n, m)) {
  84. printf("System is in Deadlock.\n");
  85. } else {
  86. printf("No Deadlock Detected.\n");
  87. }
  88.  
  89. return 0;
  90. }
  91.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
No Deadlock Detected.