Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Banker's Algorithm, detects if system is in a safe state. Returns 0 if not safe returns 1 if safe.
- int bankers(){
- // Allocate memory for temporary node
- struct node* tempNode = (struct node*) malloc(sizeof(struct node));
- // Init variables
- int currDevices = CURR_DEV;
- int n_processes = 0;
- int found = 0;
- int count = 0;
- int i = 0;
- // Count elements in lists
- n_processes += countLL(waitQueue);
- n_processes += countLL(readyQueue);
- // Allocate an array of nodes.
- node** nodeList = (struct node**) malloc((sizeof(struct node) * n_processes));
- int* safeSequence = malloc(sizeof(int) * n_processes);
- // Populate node array, set all safe flags to 0
- if (waitQueue != NULL) {
- tempNode = waitQueue;
- while (tempNode != NULL) {
- tempNode->bankerSafe = 0;
- nodeList[i] = tempNode;
- i++;
- tempNode = tempNode->next;
- }
- }
- if (readyQueue != NULL) {
- tempNode = readyQueue;
- while (tempNode != NULL) {
- tempNode->bankerSafe = 0;
- nodeList[i] = tempNode;
- i++;
- tempNode = tempNode->next;
- }
- }
- for(i = 0; i < n_processes; i++){
- printf("JOB %d ", nodeList[i]->jobNum);
- }
- //Bankers
- while(count < n_processes){
- found = 0;
- //Check if the needs of the node are less than the current dev.
- for(i = 0; i < n_processes; i++){
- //If not already finished
- printf("Currently on job %d , requesting %d devices of %d current devices \n", nodeList[i]->jobNum, nodeList[i]->requestedDevices, currDevices );
- if(nodeList[i]->bankerSafe == 0){
- if(nodeList[i]->requestedDevices <= currDevices){
- nodeList[i]->bankerSafe = 1;
- //Allocate space
- currDevices -= nodeList[i]->requestedDevices;
- //Dealocate space
- currDevices += ( nodeList[i]->devices + nodeList[i]->requestedDevices );
- //add to safe sequence
- safeSequence[count] = nodeList[i]->jobNum;
- count = count + 1;
- found = 1;
- }
- }
- }
- if(found == 0){
- printf("DEADLOCK DETECTED - SYSTEM IS NOT IN A SAFE STATE");
- free(nodeList);
- free(safeSequence);
- return 0;
- }
- }
- printf("System is in a safe state! \n");
- printf("The following sequence is safe, as determined by Banker's Algorithm: ");
- for(i = 0; i < n_processes - 1; i++){
- printf("%d -> ", safeSequence[i]);
- }
- printf("%d \n", safeSequence[i]);
- free(nodeList);
- free(safeSequence);
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement