操作系统 银行家算法模拟实现
功能函数:
2.check_allocate();检查分配,模拟分配
思路:
1)先判断所申请的资源是否大于所需求的资源即tmp_source > need[tmp_process],若大于则失败。否则继续。
2)再判断所申请的资源是否大于系统所能使用的资源即tmp_source > resource,若大于则失败,否则继续。
3)再模拟分配,判断是否安全,使用判断安全的功能函数,若安全则完成此次分配,否则返回之前的状态。
代码:
int check_allocate(int process_count,int source_count,int **allocation,int **claim,int **need,int *resource,int tmp_process,int *tmp_source)//检查分配,模拟分配
{
int j;
int flag = DANGER;//判断分配后是否安全
//保存改变前的值
int *save_resource;
int *save_need;
int *save_allocation;
for(j = 0; j < source_count; j++)
{
if(tmp_source[j] > need[tmp_process][j])
{
printf("\n**申请的资源大于所需求的资源**\n");
printf("******申请失败*******\n");
return flag;
}
}
for(j = 0; j < source_count; j++)
{
if(tmp_source[j] > resource[j])
{
printf("\n**申请的资源大于系统所能使用的资源**\n");
printf("********申请失败********\n");
return flag;
}
}
save_resource = (int *)malloc(sizeof(int) * source_count);
save_allocation = (int *)malloc(sizeof(int) * source_count);
save_need = (int *)malloc(sizeof(int) * source_count);
//模拟分配
for(j = 0; j < source_count; j++)
{
//保存以前的值
save_resource[j] = resource[j];
save_allocation[j] = allocation[tmp_process][j];
save_need[j] = need[tmp_process][j];
resource[j] -= tmp_source[j];
allocation[tmp_process][j] += tmp_source[j];
need[tmp_process][j] -= tmp_source[j];
//判断当前进程是否完成,若完全增加当前可用资源
is_done(source_count,tmp_process,allocation,need,resource);
}
flag = isSafe(process_count,source_count,allocation,need,resource);
if(DANGER == flag)//不安全,申请失败,返回原来的值
{
for(j = 0; j < source_count; j++)
{
resource[j] = save_resource[j];
allocation[tmp_process][j] = save_allocation[j];
need[tmp_process][j] = save_need[j];
}
printf("\n*****不安全,申请失败*****\n");
printf("*******返回原来的值******\n");
}
else
{
printf("\n*****安全,申请成功!****\n");
}
free(save_resource);
free(save_need);
free(save_allocation);
return flag;
}