Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. // Banker's Algorithm, detects if system is in a safe state. Returns 0 if not safe returns 1 if safe.
  2. int bankers(){
  3. // Allocate memory for temporary node
  4. struct node* tempNode = (struct node*) malloc(sizeof(struct node));
  5.  
  6. // Init variables
  7. int currDevices = CURR_DEV;
  8. int n_processes = 0;
  9. int found = 0;
  10. int count = 0;
  11. int i = 0;
  12.  
  13. // Count elements in lists
  14. n_processes += countLL(waitQueue);
  15. n_processes += countLL(readyQueue);
  16.  
  17. // Allocate an array of nodes.
  18. node** nodeList = (struct node**) malloc((sizeof(struct node) * n_processes));
  19. int* safeSequence = malloc(sizeof(int) * n_processes);
  20.  
  21. // Populate node array, set all safe flags to 0
  22. if (waitQueue != NULL) {
  23. tempNode = waitQueue;
  24. while (tempNode != NULL) {
  25. tempNode->bankerSafe = 0;
  26. nodeList[i] = tempNode;
  27. i++;
  28. tempNode = tempNode->next;
  29. }
  30. }
  31. if (readyQueue != NULL) {
  32. tempNode = readyQueue;
  33. while (tempNode != NULL) {
  34. tempNode->bankerSafe = 0;
  35. nodeList[i] = tempNode;
  36. i++;
  37. tempNode = tempNode->next;
  38. }
  39. }
  40.  
  41. for(i = 0; i < n_processes; i++){
  42. printf("JOB %d ", nodeList[i]->jobNum);
  43. }
  44.  
  45. //Bankers
  46. while(count < n_processes){
  47. found = 0;
  48.  
  49. //Check if the needs of the node are less than the current dev.
  50. for(i = 0; i < n_processes; i++){
  51. //If not already finished
  52. printf("Currently on job %d , requesting %d devices of %d current devices \n", nodeList[i]->jobNum, nodeList[i]->requestedDevices, currDevices );
  53. if(nodeList[i]->bankerSafe == 0){
  54. if(nodeList[i]->requestedDevices <= currDevices){
  55. nodeList[i]->bankerSafe = 1;
  56.  
  57. //Allocate space
  58. currDevices -= nodeList[i]->requestedDevices;
  59.  
  60. //Dealocate space
  61. currDevices += ( nodeList[i]->devices + nodeList[i]->requestedDevices );
  62.  
  63. //add to safe sequence
  64. safeSequence[count] = nodeList[i]->jobNum;
  65. count = count + 1;
  66.  
  67. found = 1;
  68. }
  69. }
  70. }
  71. if(found == 0){
  72. printf("DEADLOCK DETECTED - SYSTEM IS NOT IN A SAFE STATE");
  73. free(nodeList);
  74. free(safeSequence);
  75. return 0;
  76. }
  77. }
  78.  
  79. printf("System is in a safe state! \n");
  80.  
  81. printf("The following sequence is safe, as determined by Banker's Algorithm: ");
  82.  
  83. for(i = 0; i < n_processes - 1; i++){
  84. printf("%d -> ", safeSequence[i]);
  85. }
  86.  
  87. printf("%d \n", safeSequence[i]);
  88.  
  89.  
  90. free(nodeList);
  91. free(safeSequence);
  92. return 1;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement