Question

Write a C program for:

One technique for dealing with deadlock is called “detect and recover.” In this scheme, some procedure is used

to identify when a deadlock occurs, and then another procedure is used to deal with the blocked processes. One technique to identify a deadlock is to maintain a resource graph that identifies all processes, all resources, and the relationships between them (that is, which processes exclusively own which resources, and which processes are blocked waiting for which resources), and check for cycles in the resource graph. In this assignment you will write a program that simulates the execution of multiple processes with respect to their resource allocation and resource release requests, and detect when (or if) deadlock occurs. If deadlock occurs, your program will then display a list of the processes and resources involved in the deadlock.

To simulate the behavior of the processes in the system, your program will use input that describes the sequence of actions each process takes to lock, release, and use resources. Each such action consists of a capital letter (L, U or C) immediately followed by a non-negative integer n; the interpretation of n depends on the particular action. The various actions permitted are as follows.

      If the action is L, then the process that performs the action (say process p) requests exclusive use of the resource identified by the associated value of n. (The nr resources in the system are identified by integers in the range 1 to nr.) If the resource is available (that is, not currently locked by any other process) when process p requests its use, then process p is given exclusive use of the resource and is allowed to continue. If the resource is not available, process p is blocked and placed at the end of the first-in-first-out queue of processes waiting on the resource. Process p remains on the queue until the resource becomes available and it (process p) is at the head of the queue of waiting processes. Thus the first process to block while requesting use of a resource is the process that is moved to the ready state when the resource again becomes available.

      If the action is U, process p relinquishes its exclusive use of the resource identified by n. This action will also move a single blocked process (say process q) from the head of the queue of processes waiting on this resource to the end of the system’s ready queue. Note that immediately after this waiting process (q) moves to the end of the ready queue, the process that just released the resource (p) will be moved to the end of the ready queue, just after the process that was at the head of the waiting queue (q).

      If the action is C, then the process “computes” for n units of time, maintaining exclusive use of any resources it may have previously obtained but not yet released. n will never be smaller than

1; that is, there will never be any vacuous “compute” actions in a process. Of course, the

“computation” is really fictional, and will just cause the simulated system time to increase by n.

A process terminates after it has successfully executed each of the actions specified for it in the input data. Note that we make the (unusual) assumption that if a process terminates still having exclusive use of one or more resources, then those resources are forever unavailable (at least until the next simulation)!

For example, suppose a process is described by the following sequence of actions:

L1 L2 C10 U1 U2

This process will first request exclusive use of resource 1, then exclusive use of resource 2. Next it will “compute” for 10 units of time (maintaining exclusive use of resources 1 and 2), after which it will relinquish its use of resources 1 and 2 (in that order).

There will be no more than 50 processes in the system in any simulation, and we will assume there is just a single CPU. Each process will have its own sequence of actions describing its execution, and there will be no more than 50 actions for any process. There will be no more than 50 resources in any simulation.

Each successful request for the exclusive use (L) or release (U) of a resource by a process requires one time unit to complete, and a compute action (C) requires the number of time units specified by n for that action. The example shown above will require a total of 14 time units to complete. Since all processes are assumed to be in the ready queue (in increasing process number order: 1, 2, …, np) at the beginning of a simulation, and the first time unit is numbered 0, the process in the example above will terminate at time 14.

The execution of the sequences describing each process is done in a round-robin manner. One unit of time is given to each process, in turn, starting with process 1, then process 2, …, and then process np. Execution then continues with process 1 again (assuming it didn’t block or terminate during its previous execution). Of course, when a process completes, it is no longer given any units of execution time. If a process becomes blocked, it does not receive any units of execution time until it is unblocked. If a process p requests a resource r, but is not able to immediately obtain exclusive use of r (because another process q is using it), then process p is blocked while waiting for the resource r to become available. When process q releases resource r, the first process waiting for the resource (that is, the first process in the queue of processes waiting for resource r) is moved to the end of the queue of ready processes. Note that this does not guarantee that process p will successfully obtain the resource when it next runs, since another ready process (ahead of p in the ready queue) may run and request exclusive use of the resource before p is selected for execution.

Let’s look at a complete example. Suppose we have three processes with execution action sequences as follows:

Simulation 2 in the sample input and output (below) shows the sequence in which these process actions would occur, and the time (starting at 0) when they would occur.

The set of processes in simulation 2 does not deadlock, but obviously other sequences can (see the samples for several such sequences). To detect deadlock, your program must build a resource graph (with nodes for processes and resources, and directed edges indicating resource ownership and pending resource requests), and test the graph for the existence of a cycle after each resource allocation request is made by a process. This test must be performed after each successful or unsuccessful allocation.

The Input Data

The input data will consist of a sequence of simulation test cases identified by sequential numbers starting with

1. The first line of input for each test case will contain two integers that specify the number of processes (1 ≤ np

≤ 50) and the number of resources (1 ≤ nr ≤ 50). The remaining np lines in the test case specify the actions for each of the np processes, with line i + 1 of the test case input containing the action specifications for process i. Each action specification line contains an integer na (1 ≤ na ≤ 50) that specifies the number of actions for the process and then na action specifications, each consisting of an action type (L, U, or C) followed immediately by an integer. The last test case will be followed by a line containing two integer zeroes. Sample input and output appears below, and illustrates the input format.

The Assignment

Write and test a program in C to carry out the simulation of multiple processes

executing the sequences of resource requests and computation specified by the input data, checking after each resource allocation request for the existence of deadlock by attempting to find a cycle in the resource graph. If no deadlocks occur during execution, then for each process indicate the total run time and the time when the process completed. If a deadlock does occur, indicate that fact, the time when the deadlock was detected, and the identification of the processes and resources involved in the circular wait. The samples shown below illustrate the desired output format. No extraneous output (e.g. debugging information) should appear in your output, and tracing information should not appear in the output from your solution.

The program must read from the standard input and write to the standard output.

You may use any cycle detection algorithm you wish to detect deadlock. A reasonably explicit description of a cycle detection algorithm that is appropriate for this problem is provided on Loki in the file namedcycle.txt in the csci4500 directory.

All processes will have at least one action item.

No invalid execution sequences will appear in the input. In particular, no process will attempt to release a resource it does not already possess, and no process will attempt to obtain a resource it already possesses. (There is only one unit of each resource available.)

Sample Input:

U 22 2 U11212 3 1 223 22 CCCUCC 2 2 15355425536

6 6 L2 C3 L3 C3 U2 U3 L3 C3 L1 C3 U3 U1 7 L1 C5 L2 C5 U1 U2 C3 4 C3 L3 C5 U3 5 C3 L2 C2 U2 C3 6 7 L3 C5 L5 U3 U5 C2 L6 C5 L2

Expected Output for the Sample Input (with trace enabled) Simulation 1 0: process 1: Ll 1: process 1: L2 2: process 1: C10 re

4: process 1: C8 5: process1: C7 6: process l: C6 7: process 1: C5 8: process 1:C4 9: process1: C3 10: process 1: C2 11: proc

1: process 2: L2 2: process 1: L2 2: process 2: Ll Deadlock detected at time 2 involving. (resource 1 allocated to process 1)

18: process 5: C4 19: process 6: C4 20: process 7: Ci 21: process 1: C3 22: process 2: L3 (resource 3 unavailable) 22: proces

Resources 2, 3, 4, 1


U 22 2 U11212 3 1 223 22 CCCUCC 2 2 15355425536
6 6 L2 C3 L3 C3 U2 U3 L3 C3 L1 C3 U3 U1 7 L1 C5 L2 C5 U1 U2 C3 4 C3 L3 C5 U3 5 C3 L2 C2 U2 C3 6 7 L3 C5 L5 U3 U5 C2 L6 C5 L2 C2 U2 U6 C3 9 9 9 9 L1 L2 L3 L4 C2 Ul U2 U3 U4 L2 L3 L4 L1 C2 U2 U1 U4 U3 L3 L4 L1 L2 C2 Ul U2 U3 U4 L4 L1 L2 L3 C2 U2 U1 U4 U3
Expected Output for the Sample Input (with trace enabled) Simulation 1 0: process 1: Ll 1: process 1: L2 2: process 1: C10 resource1 allocated to process 1) (resource 2 allocated to process 1) 3: process 1: C9
4: process 1: C8 5: process1: C7 6: process l: C6 7: process 1: C5 8: process 1:C4 9: process1: C3 10: process 1: C2 11: process 1: Cl 12: process : Ul (resource1 released) 13: process 1: U2 (resource 2 released) (process 1 terminated) All processes successfully terminated Process 1: run time= 14, ended at 14 Simulation 2 0: process l: Ll 1: process 2: Ll 1: process 3: L3 2: process l: L2 (resource 1 allocated to process 1) (resource 1 unavailable) (resource 3 allocated to process 3) (resource 2 allocated to process 1) 3: process 3: C5 4: process1: C2 5: process 3: C4 6: process1: cl 7: process 3: C3 8: process 1: Ui (resource 1 released) (process 2 unblocked) 9: process 3: C2 10: process 2: Ll (resource 1 allocated to process 2) 11: process 1: U2 (resource 2 released) (process 1 terminated) 12: process 3: Cl 13: process 2: L2 (resource 2 allocated to process 2) 14: process 3: U3 (resource 3 released) 15: process 2: C2 16: process 3: C2 17: process 2: C1 18: process 3: Cl (process 3 terminated) (resource1 released) (resource 2 released) 19: process 2: Ul 20: process 2: U2 (process 2 terminated) All processes successfully terminated Process1 run time-6, ended at 12 Process 2: run time-6, ended at 21 Process 3: run time9, ended at 19 Simulation 3 0: process1: Ll
1: process 2: L2 2: process 1: L2 2: process 2: Ll Deadlock detected at time 2 involving. (resource 1 allocated to process 1) (resource 2 allocated to process 2) (resource 2 unavailable) (resource 1 unavailable) Processes 1, 2 Resources 2, 1 Simulation4 0: process1: Ll (resource 1 allocated to process 1) (resource 2 allocated to process 2) (resource 3 allocated to process 3) 1: process 2: L2 2: process 3: L3 3: process 1: C3 4: process 2: C3 5: process 3: C3 6: process 1: C2 7: process 2: C2 8: process 3: C2 9: process1: cl 10: process 2: C1 11: process 3: C1 12: process : L2 12: process 2: L3 12: process 3: Ll Deadlock detected at time 12 involving... (resource 2 unavailable) (resource 3 unavailable) (resource 1 unavailable) Processes 1, 2, 3 Resources 2, 3, 1 Simulation 5 0: process l: Ll (resource 1 allocated to process 1) 1: process 2: C3 2: process 3: C3 3: process 4: L4 4: process 5: L3 5: process 6: L6 6: process 7: L5 (resource 4 allocated to process 4) (resource 3 allocated to process 5) (resource 6 allocated to process 6) (resource 5 allocated to process 7) 7: process 1: C5 8: process 2: C2 9: process 3: C2 10: process 4: C6 11: process 5: C5 12: process 6: C5 13: process 7: C2 14: process 1: C4 15: process 2: C1 16: process 3: Cl 17: process 4: C5
18: process 5: C4 19: process 6: C4 20: process 7: Ci 21: process 1: C3 22: process 2: L3 (resource 3 unavailable) 22: process 3: L2 (resource 2 allocated to process 3) 23: process 4: C4 24: process 5: C3 25: process 6: C3 26: process 7: L4 (resource 4 unavailable) 26: process: C2 27: process 3: C2 28: process 4: C3 29: process 5: C2 30: process 6: C2 31: process 1: C1 32: process 3: Cl 33: process 4: C2 34: process 5: Cl 35: process 6: Cl 36: process : L2 (resource 2 unavailable) 36: process 3: U2 (resource 2 released (process 1 unblocked) 37: process 4: C1 38: process 5: L5 38: process 6: L2 39: process 1: L2 39: process 3: C3 (resource 5 unavailable) (resource 2 allocated to process 6) (resource 2 unavailable) 40: process 4: L3 (resource 3 unavailable) Deadlock detected at time 40 involving... Processes 4, 5, 7 Resources 3, 5, 4 Simulation 6 0: process l: Ll 1: process 2: L2 2: process 3: L3 3: process 4: L4 4: process l: L2 4: process 2: L3 4: process 3: L4 : process 4: Ll Deadlock detected at time 4 involving. (resource 1 allocated to process 1) (resource 2 allocated to process 2) (resource 3 allocated to process 3) (resource 4 allocated to process 4) (resource 2 unavailable) (resource 3 unavailable) (resource 4 unavailable) (resource 1 unavailable) Processes 1, 2, 3, 4
Resources 2, 3, 4, 1
0 0
Add a comment Improve this question Transcribed image text
Answer #1

In the program, mainly there are four packages
main
-DeadlockDetector
-Log
manager
-Resource
-ResourceManager
process
-Process
-ProcessRunner
work
-ReleaseResourceTask
-RequestResourceTask
-Task
-TaskFactory
-WorkTask

**After successful compilation enter the given input
--------------------------------------------------------------------
DeadlockDetector.java
------------------------------
package main;

/*
*
* Main entry point for the program. Performs input operations
* to find out how many processes and resources are involved in the
* simulation, then creates a ProcessRunner.
* Continues until the number of processes and resources inputted
* are both 0's.
*/

import process.ProcessRunner;

import java.util.Scanner;

public class DeadlockDetector {
    /* Reading the input from standard input. */
    private static Scanner in;

    public static void main(String[] args) {

        /* See if the user requested verbose or normal mode. */
        if (args.length != 0) {
            Log.logLevel = Log.TRACE;
        } else {
            Log.logLevel = Log.INFO;
        }

        int simulationNumber = 0;

        in = new Scanner(System.in);

        while (true) {
            /* From input, how many of each object required. */
            int numProcesses = in.nextInt();
            int numResources = in.nextInt();

            /* If both zero, user wants to exit program. */
            if (numProcesses == 0 && numResources == 0) {
                break;
            }

            /* Print which simulation this is on. */
            simulationNumber++;
            Log.info("Simulation %d\n", simulationNumber);

            /* Create the processes, resources, and resource manager. */
            ProcessRunner runner = new ProcessRunner(in, numProcesses, numResources);
            /* Run the simulation. */
            runner.runProcesses();
        }
    }
}
--------------------------------------------------------------------
Log.java
------------------------------
package main;

/*
*
* Class used for easily switching between verbose mode and normal mode.
* Output should be done using Log.info or Log.trace instead of
* System.out.println.
*/

public class Log {
    public static final int TRACE = 0;
    public static final int INFO = 1;
    /* How much logging should be performed. */
    public static int logLevel;
    /* Temporary storage for trace logic. */
    private static StringBuffer trace = new StringBuffer();

    public static void trace(String format, Object... args) {
        trace(String.format(format, args));
    }

    /* Method for verbose tracing. */
    public static void trace(String s) {
        if(logLevel <= TRACE) {
            trace.append(s);
        }
    }

    /* Method to actually trigger the trace being printed.                   */
    /* Prints the passed information before the previous traced information. */
    public static void printTrace(String format, Object... args) {
        if (logLevel <= TRACE) {
            System.out.printf(format, args);
            System.out.print(trace);
            trace = new StringBuffer();
        }
    }

    /* Print at the normal level using a format string. */
    public static void info(String format, Object... args) {
        info(String.format(format, args));
    }

    /* Print a string at the normal level. */
    public static void info(String s) {
        if (logLevel <= INFO) {
            System.out.print(s);
        }
    }
}
--------------------------------------------------------------------
REsource.java
------------------------------
package manager;

/*
* Object representing a resource in the simulation.
* Contains a reference to a process that owns this resource, which is
* null when the resource is available.
*/

import main.Log;
import process.Process;

public class Resource {
    public static final int SUCCESS = 0;
    public static final int FAIL = -1;
    /* Which process currently holds this resource. */
    protected Process processAssigned;
    /* The ID for this resource. */
    private int resourceId;

    public Resource(int resourceId) {
        this.resourceId = resourceId;
    }

    /* Method for requesting this resource.           */
    /* Returns SUCCESS if the resource was available. */
    /* Returns FAIL if the resource was unavailable. */
    public int requestResource(Process requester) {
        if (processAssigned == null) {
            Log.trace("\t(resource %d allocated)\n", resourceId);
            processAssigned = requester;
            return SUCCESS;
        } else {
            Log.trace("\t(resource %d unavailable)\n", resourceId);
            requester.requestedResource = this;
            return FAIL;
        }
    }

    /* Method for releasing this resource.                 */
    /* Returns SUCCESS if the owner of resource made call. */
    /* Returns FAIL if the improper owner made the call.   */
    public int releaseResource(Process requester) {
        if (processAssigned == requester) {
            Log.trace("\t(resource %d released)\n", resourceId);
            processAssigned = null;
            return SUCCESS;
        } else {
            return FAIL;
        }
    }

    /* Return which resource this is. */
    public int getResourceId() {
        return resourceId;
    }
}
--------------------------------------------------------------------
ResourceManager.java
------------------------------
package manager;

/*
* Coordinator of resource requests. Attempts to allocate a resource
* given a resource id (1-based counting).
* Whenever a process releases a resource, the blocked queue is checked
* for any process blocking for that resource. If a process is found, it
* is moved to the ready queue.
* Whenever a process blocks for a resource, the simulation is checked
* for any deadlock situations.
*/

import main.Log;
import process.Process;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class ResourceManager {
    /* Full listing of all resources. */
    private Resource[] resources;
    /* Queue of processes ready to execute. */
    private Queue<Process> readyQueue;
    /* Queue of processes waiting for a resource. */
    private List<Process> blockedQueue;

    /* Create a resource manager with the given number of resources. */
    public ResourceManager(int numResources, Queue<Process> readyQueue,
                           List<Process> blockedQueue) {
        /* Create array of resources available to the processes. */
        resources = new Resource[numResources];
        for (int i = 0; i < numResources; ++i) {
            resources[i] = new Resource(i + 1);
        }

        this.readyQueue = readyQueue;
        this.blockedQueue = blockedQueue;
    }

    /* Look into resource array and get a particular resource. */
    /* Converts from the 1-based counting to 0-based.          */
    public Resource getResourceById(int id) {
        return resources[id - 1];
    }

    /* Attempt to obtain exclusive use of a resource. */
    /* Check for deadlock if it blocks.               */
    public int requestResource(Process requester, int id) {
        Resource resource = getResourceById(id);

        if (resource.requestResource(requester) == Resource.SUCCESS) {
            return Resource.SUCCESS;
        } else {
            checkForDeadlock(requester);
            return Resource.FAIL;
        }
    }

    /* Release exclusive use of a resource by a process.      */
    /* If a process is waiting for this resource, it is moved */
    /* to the ready queue to be executed.                     */
    public int releaseResource(Process requester, int id) {
        Resource resource = getResourceById(id);

        /* Release the resource and check that it was released properly. */
        if (resource.releaseResource(requester) == Resource.SUCCESS) {
            /* Check if any other processes were waiting on this resource. */
            for (Process process : blockedQueue) {
                if (process.requestedResource == resource) {
                    Log.trace("\t(process %d unblocked)\n", process.getProcessId());
                    /* Move the process from blocked to ready queue. */
                    blockedQueue.remove(process);
                    readyQueue.add(process);
                    /* Signify that the process is no longer waiting. */
                    process.requestedResource = null;
                    break;
                }
            }

            return Resource.SUCCESS;
        } else {
            return Resource.FAIL;
        }
    }

    /* See if there is a deadlock by looking at the "resource graph." */
    /* This is actually just following references from process to     */
    /* resource until null is found, or the original process.         */
    private void checkForDeadlock(Process requester) {
        /* A list of processes involved in a deadlock. */
        List<Process> involvedProcesses = new LinkedList<Process>();
        /* A list of resources involved in a deadlock. */
        List<Resource> involvedResources = new LinkedList<Resource>();
        involvedProcesses.add(requester);

        while (true) {
            /* Look at the resource requested by the process. */
            involvedResources.add(0, involvedProcesses.get(0).requestedResource);
            if (involvedResources.get(0) == null) {
                break; /* If no resource, there is no deadlock. */
            }

            /* Look at the process holding the resource. */
            involvedProcesses.add(0, involvedResources.get(0).processAssigned);
            if (involvedProcesses.get(0) == null) {
                break; /* If no process, there is no deadlock. */
            }

            /* If we looped back to the original process, there is a deadlock! */
            if (requester == involvedProcesses.get(0)) {
                /* Remove duplicate reference to original process. */
                involvedProcesses.remove(0);
                throw new RuntimeException(createDeadlockMessage(
                        involvedProcesses,
                        involvedResources));
            }
        }
    }

    /* Format the message that will be thrown in an exception back up */
    /* to the process runner. The process runner then prints it.      */
    private String createDeadlockMessage(List<Process> involvedProcesses,
                                         List<Resource> involvedResources) {
        StringBuilder sb = new StringBuilder();

        /* List off all of the PIDs involved in the deadlock. */
        sb.append("    processes:");
        for (Process process : involvedProcesses) {
            sb.append(" ").append(process.getProcessId());
        }

        /* List off all of the resource IDs involved in the deadlock. */
        sb.append("\n    resources:");
        for (Resource resource : involvedResources) {
            sb.append(" ").append(resource.getResourceId());
        }

        return sb.toString();
    }
}
--------------------------------------------------------------------
Process.java
------------------------------
package process;

/*
* Object representing a process in the simulation.
* Contains a list of tasks to be executed. Also has a reference to a
* resource that is being requested by this process, which is null when
* the process is not blocking for any resources.
*/

import main.Log;
import manager.Resource;
import manager.ResourceManager;
import work.Task;

public class Process {
    /* Which resource the process is waiting on. */
    public Resource requestedResource;
    /* When this process finished running in time. */
    public int endTime;
    /* List of tasks to be performed by this process. */
    private Task[] tasks;
    /* Which task is to be executed next. Begins with 0. */
    private int currentTask;
    /* How long this process has taken to run. */
    private int runTime;
    /* The ID for this process. */
    private int processId;

    public Process(int processId, Task[] tasks) {
        this.tasks = tasks;
        currentTask = 0;
        runTime = 0;
        /* Signify it hasn't ended yet. */
        endTime = -1;

        this.processId = processId;
    }

    /* Executes the next tasks in the process. */
    public void execute(ResourceManager manager) {
        /* Update the total running time. */
        runTime++;

        Log.trace("process %d: ", processId);

        /* Run the current task and capture the return value. */
        int taskCode = tasks[currentTask].execute(manager, this);

        /* See if task completed successfully. */
        if (taskCode == Task.DONE) {
            /* Execute next task when process is next invoked. */
            currentTask++;
        } else if (taskCode == Task.BLOCKED) {
            /* Failed requests for resources count as zero time. */
            runTime--;
        }
    }

    /* See if this process has any tasks left to execute. */
    public boolean hasWork() {
        return currentTask < tasks.length;
    }

    /* See if this process is blocked waiting for a resource. */
    public boolean isBlocked() {
        return requestedResource != null;
    }

    /* See how many steps this process took to execute. */
    public int getRunTime() {
        return runTime;
    }

    /* Return which process this is. */
    public int getProcessId() {
        return processId;
    }
}
--------------------------------------------------------------------
ProcessRunner.java
------------------------------
package process;

/*
* Main runner for the simulation. Creates the ready and blocked queues.
* Creates the processes with all of their tasks using the standard input.
* Takes processes from the ready queue and runs them.
*/

import main.Log;
import manager.ResourceManager;
import work.Task;
import work.TaskFactory;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;

public class ProcessRunner {
    /* Full listing of all processes. */
    private Process[] processList;
    /* Queue of processes ready to execute. */
    private Queue<Process> readyQueue;
    /* Queue of processes waiting for a resource. */
    private List<Process> blockedQueue;
    /* Controls granting and releasing resources. */
    private ResourceManager manager;

    /* Read from the system input to create a queue of processes */
    /* that each contain a list of tasks. Put all processes into */
    /* the ready queue initially.                                */
    public ProcessRunner(Scanner in, int numProcesses, int numResources) {
        /* How many tasks are in the current process. */
        int numTasks;
        /* The two parameters for the task. */
        int operation, n;
        Task[] processTasks;

        /* Create the object to list all processes. */
        processList = new Process[numProcesses];

        /* Set up the ready queue for execution. */
        readyQueue = new LinkedList<Process>();
        blockedQueue = new LinkedList<Process>();

        manager = new ResourceManager(numResources, readyQueue, blockedQueue);

        /* Create all of the processes according to the input. */
        for (int i = 0; i < numProcesses; ++i) {
            numTasks = in.nextInt();            /* See how many tasks. */
            processTasks = new Task[numTasks];
            /* Populate the list of tasks to be executed for the process. */
            for (int j = 0; j < numTasks; ++j) {
                operation = in.nextInt();
                n = in.nextInt();

                processTasks[j] = TaskFactory.createTask(operation, n);
            }
            /* Create the new process with the appropriate tasks. */
            Process process = new Process(i + 1, processTasks);
            /* Add the process to the list for final reporting. */
            processList[i] = process;
            /* Set up the process to be run. */
            readyQueue.add(process);
        }
    }

    public void runProcesses() {
        int currentStep = -1;

        /* Run until the ready queue is empty. */
        while (readyQueue.peek() != null) {
            Process currentProcess = readyQueue.remove();

            /* Update how many tasks have been executed. */
            currentStep++;

            /* Attempt to execute all of the processes, which may */
            /* throw an error if a deadlock is detected.          */
            try {
                currentProcess.execute(manager);
            } catch (RuntimeException e) {
                Log.printTrace("%d: ", currentStep);

                Log.info("Deadlock detected at time %d involving...\n%s\n\n",
                        currentStep,
                        e.getMessage());
                return;
            }

            Log.printTrace("%d: ", currentStep);

            /* Add the process to the correct queue according to its state. */
            if (currentProcess.isBlocked()) {
                currentStep--;

                blockedQueue.add(currentProcess);
            } else if (currentProcess.hasWork()) {
                readyQueue.add(currentProcess);
            } else {
                /* Trace that this process successfully terminated. */
                Log.printTrace("\t(process %d terminated)\n", currentProcess.getProcessId());
                currentProcess.endTime = currentStep;
            }
        }

        /* Did not receive any exceptions from deadlocks, */
        /* so everything terminated correctly.            */
        Log.info("All processes successfully terminated.\n");
        for (Process process : processList) {
            Log.info("Process %d: run time = %d, ended at %d\n",
                    process.getProcessId(),
                    process.getRunTime(),
                    process.endTime);
        }

        /* Output one final line to separate from next process. */
        Log.info("\n");
    }
}
--------------------------------------------------------------------
ReleaseResourceTask.java
------------------------------
package work;

/*
*
* Task that releases exclusive access to a previously allocated resource.
*/

import main.Log;
import manager.Resource;
import manager.ResourceManager;
import process.Process;

public class ReleaseResourceTask extends Task {

    private int resource;

    public ReleaseResourceTask(int resource) {
        this.resource = resource;
    }

    /* Release a resource. */
    @Override
    public int execute(ResourceManager manager, Process runner) {
        Log.trace("(%d,%d)\n", TaskFactory.RELEASE_RESOURCE, resource);

        if(manager.releaseResource(runner, resource) == Resource.SUCCESS) {
            return DONE;
        } else {
            return NOT_DONE;
        }
    }
}
--------------------------------------------------------------------
RequestResourceTask.java
------------------------------
package work;

/*
*
* Task that requests exclusive access to a resource.
*/

import main.Log;
import manager.Resource;
import manager.ResourceManager;
import process.Process;

public class RequestResourceTask extends Task {

    private int resource;

    public RequestResourceTask(int resource) {
        this.resource = resource;
    }

    /* Request exclusive access to a resource. */
    @Override
    public int execute(ResourceManager manager, Process runner) {
        Log.trace("(%d,%d)\n", TaskFactory.REQUEST_RESOURCE, resource);
        if (manager.requestResource(runner, resource) == Resource.SUCCESS) {
            return DONE;
        } else {
            return BLOCKED;
        }
    }
}
--------------------------------------------------------------------
Task.java
------------------------------
package work;

/*
*
* Interface for a task - the basic unit of work in the simulation.
*/

import manager.ResourceManager;
import process.Process;

public abstract class Task {
    public static final int DONE = 0;
    public static final int NOT_DONE = 1;
    public static final int BLOCKED = 2;

    /* Performs the work for a given task.            */
    /* Returns DONE when the task has completed.      */
    /* Returns NOT_DONE when the task still has work. */
    public abstract int execute(ResourceManager manager, Process runner);
}
--------------------------------------------------------------------
TaskFactory.java
------------------------------
package work;

/*
* Author: Josh DeWitt
* Written for Program 2 during CSCI4500 in 2013 Summer session.
*
* Convenient method for creating tasks given two integers.
* The first integer is the action, and the second integer's meaning
* depends on the first integer.
*/

public class TaskFactory {
    public static final int REQUEST_RESOURCE = 1;
    public static final int RELEASE_RESOURCE = 2;
    public static final int COMPUTE = 3;

    /* Creates a task given two integers. */
    public static Task createTask(int action, int n) {
        switch(action) {
            case REQUEST_RESOURCE:
                return new RequestResourceTask(n);
            case RELEASE_RESOURCE:
                return new ReleaseResourceTask(n);
            case COMPUTE:
                return new WorkTask(n);
            default:
                throw new IllegalArgumentException("Action #" + action + " is invalid.");
        }
    }
}
--------------------------------------------------------------------
WorkTask.java
------------------------------
package work;

/*
*
* Task that simulations computation for many executions.
*/

import main.Log;
import manager.ResourceManager;
import process.Process;

public class WorkTask extends Task{

    private int duration;

    public WorkTask (int duration) {
        this.duration = duration;
    }

    /* Execute one more iteration. Return DONE when finished. */
    @Override
    public int execute(ResourceManager manager, Process process) {
        Log.trace("(%d,%d)\n", TaskFactory.COMPUTE, duration);

        duration--;

        /* Check if the work has been completed and return as appropriate. */
        if(duration == 0) {
            return Task.DONE;
        } else {
            return Task.NOT_DONE;
        }
    }
}
DeadDetector - [CAUsersSwapniDeadDetector) - [DeadDetector] -. tectorjava Intelli IDEA 2017.1.4 Eile Edit View Navigate Code IJ DeadDetector CAUserstSwapniDeadDetector) - [DeadDetector] .rWorkTask.java Intelli IDEA 2017.1.4 Eile Edit View Navigate Co

Add a comment
Know the answer?
Add Answer to:
Write a C program for: One technique for dealing with deadlock is called “detect and recover.” In...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Part B (10) Deadlock Avoidance Consider the following maximum-claim reusable resource system with four processes and...

    Part B (10) Deadlock Avoidance Consider the following maximum-claim reusable resource system with four processes and three resource types. The maximum claim matrix is given by C [4 3 5 11 1 41 1 4 6 13 1 6] where Cij denote maximum claim of process i for resourcej. The total units of each resource type are given by the vector (5, 8, 15). The current allocation of resources is given by the matrix To 1 4] 2 0 1...

  • Round Robin Simulation in C++ using queue Description: Write a program that utilizes STL queue that...

    Round Robin Simulation in C++ using queue Description: Write a program that utilizes STL queue that simulates the round robin process scheduling algorithm. Requirement: - write a class Process that holds following integer information: id, arrival_time, time_needed, finished_time. - read and initiate 5 Process objects from associated file (round_robin.txt) - file format: id, arrival_time, time_needed - once a process is finished, mark its finished_time accordingly. - CPU time frame: 4. - utilize a queue for process scheduling. - store finished...

  • Please give an explanation for the answers as well. 1. A system has three processes (P1,...

    Please give an explanation for the answers as well. 1. A system has three processes (P1, P2, and P3) and three resources (R1, R2, and R3). There is one instance of RI, two instances of R2, and three instances of R3. PI holds RI and one instance of R3 and is requesting one instance from R2. P2 holds one instance of R3 and is requesting RI and one instance from R2. P3 holds two instances of R2 and one instance...

  • box all answers please for a thumbs up Learning Goal: To reduce series-parallel combinations of inductors...

    box all answers please for a thumbs up Learning Goal: To reduce series-parallel combinations of inductors or capacitors to an equivalent inductance or capacitance. Inductors in series and parallel combine like resistors in series and parallel. It is possible to use Kirchhoff's current law to find the current through the equivalent inductance. Moreover, capacitors in series combine like resistors in parallel and vice versa. It is possible to use Kirchhoff's voltage law to find the voltage across the equivalent capacitance....

  • Let I represent an execution of init(s), W of wait(s), and S of signal(s). Then, for...

    Let I represent an execution of init(s), W of wait(s), and S of signal(s). Then, for example, IWWS represents the sequence of calls init(s), wait(s), wait(s), and signal(s) by some processes in an operating system. For each of the following sequences of calls, state the value of s and the number of processes blocked after the last call in the sequence: (b) IS (c) ISSSW (d) IWWWS (e) ISWWWW Each of the following code fragments contains a bug in the...

  • M Review Constants Part A - Determine the equivalent inductance to the right of terminals b...

    M Review Constants Part A - Determine the equivalent inductance to the right of terminals b and e, including L4 Learning Goal: To reduce series-parallel combinations of inductors or capacitors to an equivalent inductance or capacitance. Inductors in series and parallel combine like resistors in series and parallel. It is possible to use Kirchhoffs current law to find the current through the equivalent inductance. Moreover, capacitors in series combine like resistors in parallel and vice versa. It is possible to...

  • a) Write a C-program that creates a chain of 10 processes and prints out their process...

    a) Write a C-program that creates a chain of 10 processes and prints out their process ids and relationships. For example, process 1 is the parent of process 2, process 2 is the parent of process 3, process 3 is the parent of 4 and so on. Each child has to print out all her ancestors identified by the process ids. b) Write a C-program that creates a fan of 10 processes. That is, process 1 is the parent of...

  • I want to this question solution by programming c code. I need this solution as soon...

    I want to this question solution by programming c code. I need this solution as soon as possible i have to submit this code after 24 hours. please someone help this question thanks :D Programming Question: (15pts) Assume a finite number of resources of a single resource type must be managed. Processes may ask for a number of these resources and will return them once finished. If all resources are in use the request is denied and the process terminates....

  • A Review Constants Part E - Determine the equivalent capacitance across terminals a and b Learning...

    A Review Constants Part E - Determine the equivalent capacitance across terminals a and b Learning Goal: To reduce series-parallel combinations of inductors or capacitors to an equivalent inductance or capacitance. Inductors in series and parallel combine like resistors in series and parallel. It is possible to use Kirchhoff's current law to find the current through the equivalent inductance. Moreover, capacitors in series combine like resistors in parallel and vice versa. It is possible to use Kirchhoff's voltage law to...

  • This assignment requires you to create simulations for different scheduling algorithms commonly employed by operating systems...

    This assignment requires you to create simulations for different scheduling algorithms commonly employed by operating systems to achieve multiprogramming. All problems in this assignment assume the following: The simulations you will be creating are for a uniprocessor system (single CPU). Processes in these simulations will require CPU bursts of one or more time units followed by I/O bursts of one or more time units. For simplicity’s sake, when more than one process is executing its I/O burst at the same...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT