我正在制作一个简单的银行家算法模拟器。当我将需求与可用资源进行比较时,它适用于1循环。但是,我无法再次重申链表。 (在银行家算法中,你可能只能运行链表中的最后一个。在这种情况下,你必须再次浏览链表,看看是否可以运行[这是不起作用的部分])我认为它与指针有关,但我不确定是什么。
struct LL //linked list structure(pcb)
{
LL_pid pid;
int alloc[15];
int max[15];
int need[15];
int finish;//flag to show if finished
PCB *next; //points to next pcb in linked list
};
继承我难倒的地方。我添加了一些测试printfs并意识到它不会重复循环(可能因为pcb_head的指针现在为null)?
void makeBANK(PCB *pcb_head, int avail[15]){
PCB *temp=pcb_head;
int availnew[15];
int x=0;
for(x=0;x<processCount;x++){//get all the available resources
availnew[x]=avail[x];
}
int alldone=0;//check if all processes could run
int possible=0;//check if its possible if a process can run with current available resources
int y=0;
int i=0;
int z=0;
for(y=0;y<processCount;y++){//trying to iterate the linked list at least the amount of processes there are(worst case)
temp=pcb_head;
while((temp!=NULL)&&(temp->finish!=1)){//search all nodes
for(i=0;i<resourceCount;i++){//compare avail and need
if(availnew[i]>=temp->need[i]){//if possible keep 1 ,loop all
possible=1;
}
else{
possible=0;
printf("oops");
break;
}//if not possible break
}
if(possible==1){//if the possible still 1 then print
printf("%d running",temp->pid);
temp->finish=1;
alldone++;
for(z=0;z<resourceCount;z++){//add the allocated to the available
availnew[z]=availnew[z]+temp->alloc[z];
printf("avil: %d",availnew[z]);
}
}
temp=temp->next;//and go to next node(also needed for else)
}
}
if(alldone!=processCount)
printf("not safe");
else
printf("safe");
}
我对所有提示(organization..etc)持开放态度,即使我在谷歌上找不到一个可能很简单的解决方案。
答案 0 :(得分:0)
好吧,当循环到达链表末尾时(temp!= NULL)或当前进程是 完成(temp - &gt; finish = 1)。
问题是如果链表中有一个已经完成的过程会怎样?
我可以建议两种解决方案:
这是我们所处情况的演示代码:
现状:
for(i = 0; i < numberOfNodes; i++) {
temp = listHead;
while(temp != NULL && temp -> finish != 1) {
//check resource availability here
if(executionPossible = 1) { // Process can be executed
//print process id here
temp -> finish = 1;
//update number of available resources
}
temp = temp -> next;
}
}
我的解决方案(第二个):
for(i = 0; i < numberOfNodes; i++) {
int currentFinished = 0;
temp = listHead;
while(temp != NULL && currentFinished != 1) {
//check resource availability here
if(executionPossible = 1) { // Process can be executed
//print process id here and mark/set process as finished
temp -> finish = 1;
currentFinished = 1;
//update number of available resources
}
temp = temp -> next;
}
}
PS:这是我关于堆栈溢出的第一个答案。欢迎提供反馈。