Operating System—Simulation and Implementation of Banker's Algorithm

1: Experimental topic

Simulation and Realization of Banker's Algorithm

Two: The purpose of the experiment

(1) Learn more about concurrent execution of processes.

(2) Strengthen the understanding of process deadlock, and understand the concepts of safe state and unsafe state.

(3) Master the use of banker's algorithm to avoid deadlock problems.

3. Overall design (including background knowledge or basic principles and algorithms, or module introduction, design steps, etc.)

Background knowledge and rationale:

1. Concurrent execution of processes: Multiple processes run at the same time and share system resources, which may lead to resource competition and deadlock problems.

2. Deadlock: The process falls into an infinite waiting state due to competition for resources and cannot continue to execute.

3. Safe state and unsafe state: The safe state means that the system can find a resource allocation order, so that all processes can be completed smoothly, and the unsafe state means that such an allocation order cannot be found.

Banker's Algorithm Principle:

The banker's algorithm is a resource allocation strategy used to avoid process deadlocks. It judges whether the system is in a safe state based on the maximum demand for resources and the amount of allocated resources, and if so, allocates resources; if not, waits.

Design steps:

1. Define the data structure of processes and resources: It is necessary to represent information such as the identification of the process, the maximum demand, the allocated amount, and the demanded amount, as well as the total amount and available amount of resources.

2. Realize the safety status check of the banker's algorithm: traverse all processes, simulate the resource allocation process, and judge whether the system is in a safe state.

3. Realize resource allocation strategy: allocate resources according to the maximum demand and allocated amount of the process, and update the system resource status.

Four. Detailed design (including main data structures, program flow charts, key codes, etc.)

Main data structures:

Process structure: contains information such as process identification, maximum demand, allocated volume, and demand volume.

Resource structure: contains the total amount and available amount of resources.

*Enter the loop to receive resource requests input by the user.

*Judge whether the request is legal, and try to allocate resources if it is legal.

* Check the security status according to the banker's algorithm to judge whether the system is in a security status.

* If the system is in a safe state, allocate resources and update the system state.

*Output allocation results and system status.

data structure

number of processes n

Number of resource classes m

Available resource vector Available

An array containing m elements, each of which represents the number of resources available for a class. If Available[j]=K, it means that there are K resources of type Rj in the system.

Maximum demand matrix Max

An n×m matrix, which defines the maximum demand of each of the n processes in the system for m types of resources. If Max[i,j]=K, it means that the maximum number of Rj-type resources required by process i is K.

Allocation Matrix Allocation

An n×m matrix, which defines the number of resources currently allocated to each process for each type of resource in the system. If Allocation[i,j]=K, it means that the number of Rj-type resources allocated to process i is K.

Demand matrix Need

The n×m matrix is ​​used to represent the number of various resources still required by each process. If Need[i,j]=K, it means that process i still needs K resources of type Rj to complete its task.

Need[i,j]=Max[i,j]-Allocation[i,j]

Security Check Algorithm

Set up two working vectors

Work records the amount of resources currently available in the system, and the initial value is Available;

finish records whether all processes have been executed, and the initial value is a vector with length n and all values ​​are False.

Find a process from the process set that satisfies the following conditions,

finish == False;

Need <= Work;

If found, go to 3; otherwise, go to 4.

Assuming that the process acquires the resource, it can execute smoothly until it completes, thereby releasing the resource.

Work += Allocation;

Finish=True;

Execute 2

If all processes finish=True, it means safe; otherwise, the system is not safe.

*Users can choose to continue requesting resources or end the program.

 

key code:

void initial()

{

    int i;

    int j;

    printf("Please enter the process number:\n");

    scanf("%d",&n);

    printf("Please enter resource class number:\n");

    scanf("%d",&m);    

    printf("Please input available resource vector:\n");

    Available = (int*)malloc(sizeof(int)*m);

    for(i=0; i<m; i++)

        scanf("%d",&Available[i]);

    printf("Please enter the maximum demand matrix:\n");

    Max = (int**)malloc(sizeof(int*)*n);

    for(i=0; i<n; i++)

    {

        Max[i] = (int*)malloc(sizeof(int)*m);

        for(j=0; j<m; j++)

            scanf("%d",&Max[i][j]);

    }

    printf("Please enter the allocation matrix:\n");

    Allocation = (int**)malloc(sizeof(int*)*n);

    for(i=0; i<n; i++)

    {

        Allocation[i] = (int*)malloc(sizeof(int)*m);

        for(j=0; j<m; j++)

            scanf("%d",&Allocation[i][j]);

    }

    Need = (int**)malloc(sizeof(int*)*n);

    for(i=0;i<n;i++)

    {

        Need[i] = (int *)malloc(sizeof(int)*m);

        for(j=0;j<m;j++)

            Need[i][j] = Max[i][j] - Allocation[i][j];

    }

}

void request()

{

    int i,id;

    new_request = (Request*)malloc(sizeof(Request));

    new_request->req_src = (int*)malloc(sizeof(int)*m);

    printf("Please enter the ID of the process\n");

    scanf("%d",&id);

    new_request->id = id - 1;

    printf("Please enter the process application resource vector\n");

    for(i=0; i<m; i++)

        scanf("%d",&new_request->req_src[i]);

}

void process()

{

    int i = new_request->id;

    if(vector_compare(Need[i],new_request->req_src,m))

        {

            if(vector_compare(Available,new_request->req_src,m))

            {

                vector_sub(Available,new_request->req_src,m);

                vector_add(Allocation[i],new_request->req_src,m);

                vector_sub(Need[i],new_request->req_src,m);

                safe_detect();

            }

            else

            {

                printf("The resources requested by the program are greater than the current remaining resources of the system, and the execution will be postponed!\n");  

                return;

            }

                              

        }

    else

    {

        printf("The resources requested by the program are greater than the resources required by the program, and cannot be executed!\n");

        return;

    }    

    if(safe)

    {

        printf("System security, the process can be executed!\n");

        return;

    }

    else

    {

        printf("The system is not safe, the process cannot be executed!\n");

        vector_add(Available,new_request->req_src,m);

        vector_sub(Allocation[i],new_request->req_src,m);

        vector_add(Need[i],new_request->req_src,m);

        return;

    }

        

}

bool safe_detect()

{

    int *work = Available;

    bool *finish = (bool*)malloc(sizeof(bool)*n);

    int i;

    //Initialize finish

    for(i=0; i<n; i++)

        finish[i] = False;

    

    for(i=0; i<n; i++)

    {

        if(finish[i]==False&&vector_compare(work,Need[i],m))

        {

            printf("Try to execute process %d\n", i+1);

            vector_add(work,Allocation[i],m); //Try to execute the process and release resources

            finish[i] = True;

            i = -1; //After trying to allocate, check whether there is still an executable process from the beginning, considering i++, so here is -1

        }

    }

    

    for(i=0; i<n; i++)

        if(finish[i]==False)

            break;

    if(i==n)

        safe = True;

    else

        safe = False;

}

 

Five: Experimental results and analysis

This code implements the safety checking part of the Banker's algorithm. The banker's algorithm is a resource allocation and scheduling algorithm used to prevent the system from falling into a deadlock state. It judges whether there is a safe sequence by pre-calculating the maximum resource requirements of the process and the currently available resources, so that all processes can complete the execution.

The following is an analysis of the security check part of the code:

1. The safe_detect() function is used for security checks. It accepts the current system available resource vector Available, the process's maximum demand matrix Max and the allocation matrix Allocation as input.

2. An auxiliary array work and a Boolean array finish are created inside the function to record the work vector and the completion status of the process.

3. Initialize the finish array, and initialize the completion status of all processes to False.

4. The main logic for security check is a loop traversal. For each process i, judge that its completion status is False and the current available resource work is greater than or equal to the demand vector Need[i] of process i. If the conditions are met, it means that the process i can be executed, that is, try to execute the process and release the corresponding resources.

5. After attempting to execute process i, set the completion status of process i to True and increase the available resource vector work by the amount of resources allocated to process i.

6. Loop back to the very beginning and continue to search for the next process that satisfies the condition until no process that meets the condition is found or all processes are marked as completed.

Finally, check that all processes are marked as completed. If so, the system is considered safe and the variable safe is set to True; otherwise, safe is set to False.

In experiments, you can test by simulating different process and resource situations. According to the input process resource request, the system will allocate resources according to the banker's algorithm, and output the allocation result and system status. You can observe whether the system is in a safe state, as well as the allocation of resources.

6. Summary and experience

Through this experiment, I further understood the concurrent execution of processes and deadlock problems, and learned the principle and implementation of the banker's algorithm. Realize the banker's algorithm through actual coding, which deepens the understanding of the algorithm and improves the programming ability. At the same time, through the process of experimentation, I have a deeper understanding of the concept of resource competition and security status, and have a clear idea of ​​how to avoid deadlock problems. By analyzing the experimental results, I can better evaluate the security of the system and the effectiveness of the resource allocation strategy, which provides useful experience for the actual system design and development.

Guess you like

Origin blog.csdn.net/CSH__/article/details/131382772