Implementation of Banker's Algorithm for deadlock avoidance in C.

Program:

#include<stdio.h>
#define m 10
int need[m][m],maxm[m][m],allot[m][m],avail[m],P,R;

void calculateNeed(){
int i,j;
    for (i = 0 ; i < P ; i++)
        for (j = 0 ; j < R ; j++)
            need[i][j] = maxm[i][j] - allot[i][j];
}

void isSafe()
{
    int i,j,p,count=0;
    int finish[P];
calculateNeed();
for(i=0;i<P;i++)
    finish[P] = 0;
int safeSeq[P];
int work[R];
for (i = 0; i < P ; i++)
        finish[i] = 0;   
    for (i = 0; i < R ; i++)
        work[i] = avail[i];
    while (count < P)
    {
    int found = 0;
        for (p = 0; p < P; p++)
        {
            if (finish[p] == 0)
            {
                for (j = 0; j < R; j++)
                    if (need[p][j] > work[j])
                        break;
                if (j == R)
                {
                    for (int k = 0 ; k < R ; k++)
                        work[k] += allot[p][k];
                    safeSeq[count++] = p;
                    finish[p] = 1;
                    found = 1;
                }
            }
        }
        if (found == 0)
        {
        printf("System is not in safe state\n");
            return ;
        }
    }
    printf("\n\nSystem is in safe state.\n\nSafe sequence is: ");
    for (int i = 0; i < P ; i++)
        printf("-->%d",safeSeq[i]);
 
    return ;
}


int main(){
int i,j;
printf("Enter number of processes and number of resources:\n");
scanf("%d%d",&P,&R);
    printf("Enter the available resources :\n");
    for(i=0;i<R;i++)
    scanf("%d",&avail[i]);
    printf("Enter the maximum resources :\n");
    for(i=0;i<P;i++)
    for(j=0;j<R;j++)
    scanf("%d",&maxm[i][j]);
    printf("Enter the allocated resources :\n");
    for(i=0;i<P;i++)
    for(j=0;j<R;j++)
    scanf("%d",&allot[i][j]);
    isSafe();
    return 0;
}

Output:
Enter number of processes and number of resources:
5 3
Enter the available resources :
3 3 2
Enter the maximum resources :
7 5 3 
3 2 2 
9 0 2 
2 2 2 
4 3 3 
Enter the allocated resources :
0 1 0 
2 0 0 
3 0 2 
2 1 1 
0 0 2

System is in safe state.

Safe sequence is: -->1-->3-->4-->0-->2

Comments

Popular posts from this blog

Multi-programming with variable number of tasks(MVT) program in C

Multi-programming with fixed number of tasks(MFT) program in C

Linked file allocation program in C.