Deadlock Detection Algorithm Implementation In C
#include <stdio.h>
#include <conio.h>
int main()
{
int alloc[10][10],req[10][10],ins[10],avail[10],tp,tr,i,j;
int tmp[10]={0},count=0;
bool finish[10]={false},flag;
printf("Enter total no of processes:");
scanf("%d",&tp);
printf("Enter total no of resources:");
scanf("%d",&tr);
printf("Randomly Generated Allocation Matrix:\n"); //itz tp x tr order matrix
for(i=0;i
{
for(j=0;j
{
alloc[i][j]=rand()%5;
printf("\t%d",alloc[i][j]);
}
printf("\n");
}
printf("Randomly Generated Request Matrix:\n");
for(i=0;i
{
for(j=0;j
{
req[i][j]=rand()%5;
printf("\t%d",req[i][j]);
}
printf("\n");
}
printf("Randomly Generated Resource Instance Vetctor:\n");
for(i=0;i
{
ins[i]=rand()%10+tr+tp; //Just to increase resource instances
printf("\t%d",ins[i]);
}
//To calculate resource availability vector
for(i=0;i
{
for(j=0;j
{
tmp[i]+=alloc[j][i]; //sum calculated columnwise for allocation matrix
}
}
printf("\nCalculated Availability Vector:\n");
for(i=0;i
{
avail[i]=ins[i]-tmp[i];
printf("\t%d",avail[i]);
}
//main logic starts:P
while(count
{ //if finish array has all true's(all processes to running state)
//deadlock not detected and loop stops!
for(i=0;i
{
count=0;
//To check whether resources can be allocated any to blocked process
if(finish[i]==false)
{
for(j=0;j
{
if(req[i][j]<=avail[j])
{
count++;
}
}
flag=false;
if(count==tr)
{
for(j=0;j
{
avail[j]+=alloc[i][j]; //allocated reources are released and added to available!
}
finish[i]=true;
printf("\nProcess %d is transferred to running state and assumed finished",i+1);
}
else
flag=true;
}
}
count=0;
for(j=0;j
{
if(finish[j]==true)
{
count++;
}
}
}
for(i=0;i
{
if(finish[i]==false)
{
printf("\n Oops! Deadlock detected and causing process is:process(%d)\n",i+1);
break;
}
}
i=i-1;
if(finish[i]==true)
printf("\nHurray! Deadlock not detected:-)\n");
return 0;
}
/*
Sample Output:
Enter total no of processes:7
Enter total no of resources:3
Randomly Generated Allocation Matrix:
3 1 2
0 3 0
1 2 4
1 2 2
0 4 3
1 0 1
2 1 1
Randomly Generated Request Matrix:
3 2 4
2 0 2
3 2 0
4 2 2
3 4 2
3 1 1
2 4 3
Randomly Generated Resource Instance Vetctor:
11 19 14
Calculated Availability Vector:
3 6 1
Process 3 is transferred to running state and assumed finished
Process 4 is transferred to running state and assumed finished
Process 5 is transferred to running state and assumed finished
Process 6 is transferred to running state and assumed finished
Process 7 is transferred to running state and assumed finished
Process 1 is transferred to running state and assumed finished
Process 2 is transferred to running state and assumed finished
Hurray! Deadlock not detected:-)*/
No comments:
Post a Comment