很久前写过的一个北大版书上的一个例子...
用C语言写的...你参考吧...
程序代码:
#include<stdio.h>
#define SOURCE_M 3 /*系统资源种类*/
#define PROCESS_N 5 /*进程数*/
int Available[SOURCE_M]={3,3,2}; /*系统中现有各类资源数*/
int Max[PROCESS_N][SOURCE_M]={{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}}; /*各进程对各类资源的最大需求*/
int Allocation[PROCESS_N][SOURCE_M]={{0,1,0},{2,0,0},{3,0,2},{2,1,1},{0,0,2}}; /*已分配给各进程的各类资源数*/
int Need[PROCESS_N][SOURCE_M]={0}; /*各进程尚需各类资源数*/
int ProcessQueue[PROCESS_N]={0}; /*一个不死锁的进程调度*/
int cnt=0; /*计数变量*/
int CmpLower(int *p1,int *p2) /*比较函数:向量p1>p2,返回0; 向量p1<=p2,返回1*/
{
int k=0;
while(k<SOURCE_M)
{
if(*(p1+k) > *(p2+k))
return 0;
else
k++;
}
return 1;
}
int SafeCheck(int *Work) /*检查是否死锁的函数,若死锁返回0,否则返回1*/
{
int Finish[PROCESS_N]={0,0,0,0,0}; /*进程结束标记*/
int i,j;
while(1)
{
for(i=0;i<PROCESS_N;i++)
if(Finish[i]==0 && CmpLower(Need[i],Work)==1)
break;
if(i<PROCESS_N)
{
for(j=0;j<SOURCE_M;j++)
Work[j]+=Allocation[i][j]; /*回收资源*/
Finish[i]=1; /*进程结束*/
ProcessQueue[cnt++]=i+1; /*入队*/
}
else
{
for(i=0;i<PROCESS_N;i++)
if(Finish[i]==0)
break;
if(i>=PROCESS_N) /*所以进程全部安全执行*/
return 1;
else
return 0;
}
}
}
int main() /*主函数*/
{
int Request[PROCESS_N][SOURCE_M]={0}; /*某进程的资源申请向量*/
int process_n=0;
int i,j;
for(i=0;i<PROCESS_N;i++)
for(j=0;j<SOURCE_M;j++)
Need[i][j]=Max[i][j]-Allocation[i][j];
printf("输入要申请资源的进程(1—5):\n");
scanf("%d",&process_n);
while(process_n<1||process_n>5)
{
printf("输入不合法,输入要申请资源的进程(1—5):\n");
scanf("%d",&process_n);
}
process_n--;
printf("输入该进程所要申请的各资源数(A B C):\n");
for(i=0;i<SOURCE_M;i++)
scanf("%d",&Request[process_n][i]);
if(CmpLower(Request[process_n],Need[process_n])==0) /*判断申请是否超出申报最大量*/
{
printf("Error! Request > Max !\n");
return 0;
}
else if(CmpLower(Request[process_n],Available)==0) /*判断当前资源是否能满足申请*/
{
printf("\ayou must wait because there is not enough source!\n");
return 0;
}
else
{
for(i=0;i<SOURCE_M;i++) /*试探性分配*/
{
Available[i]-=Request[process_n][i];
Allocation[process_n][i]+=Request[process_n][i];
Need[process_n][i]-=Request[process_n][i];
}
}
if(SafeCheck(Available)==0) /*判断是否死锁*/
{
for(i=0;i<SOURCE_M;i++) /*若死锁则回收资源不进行分配*/
{
Available[i]+=Request[process_n][i];
Allocation[process_n][i]-=Request[process_n][i];
Need[process_n][i]+=Request[process_n][i];
}
printf("\a\a死锁!!\n");
}
else
{
printf("不发生死锁!\n存在一个进程安全序列:\n");
for(i=0;i<PROCESS_N;i++) /*输出安全的进程队列*/
printf("P%d ", ProcessQueue[i]);
printf("\n");
}
return 0;
}