#include
#include
int main(){
int avaFlag = 0;
int count = 0;
int L[5] = {0,0,0,0,0};
//无死锁
//int Allocation[5][3] = {0,1,0,2,0,0,3,0,2,2,1,1,0,0,2};
//int Need[5][3] = {7,4,3,1,2,2,6,0,0,0,1,1,4,3,1};
//int Available[3] = {3,3,2};
//有死锁
int Allocation[5][3] = {0,3,0,3,0,2,3,0,2,2,1,1,0,0,2};
int Need[5][3] = {7,2,3,0,2,0,6,0,0,0,1,1,4,3,1};
int Available[3] = {2,1,0};
printf("\n进程号\t进程已分配资源\t进程资源需求\t可利用资源\n");
printf("\tA B C\tA B C\tA B C\n");
for(int a = 0; a < 5; a++){
printf("%d\t",a);
for(int b = 0; b < 3; b++){
printf("%d ",Allocation[a][b]);
}
printf("\t");
for(int b = 0; b < 3; b++){
printf("%d ",Need[a][b]);
}
printf("\t");
if(avaFlag == 0){
for(int b = 0; b < 3; b++){
printf("%d ",Available[b]);
}
avaFlag = 1;
}
printf("\n");
}
while(1){
int i;
int flag;
for(i = 0; i < 5; i++){
for(int j = 0; j < 3; j++){
if(Need[i][j] <= Available[j] && L[i] == 0){
flag = 1;
}else{
flag = 0;
break;
}
}
if(flag == 1){
L[i] = 1;
for(int j = 0; j < 3;j++){
Available[j] = Available[j] + Allocation[i][j];
}
count++;
//printf("%d,%d,%d\n",count,i,L[i]);
break;
}
}
if(L[i] != 1){
printf("\n发生死锁!!\n");
printf("进程号\t状态\n");
for(int j = 0; j < 5; j++){
printf("%d\t%d\n",j,L[j]);
}
break;
}else if(count == 5){
printf("\n没有发生死锁!!\n",count);
printf("进程号\t状态\n");
for(int j = 0; j < 5; j++){
printf("%d\t%d\n",j,L[j]);
}
break;
}
}
}