C 重申链表(银行家算法)
我正在做一个简单的银行家算法模拟器。当我将需求与可用资源进行比较时,它在1个循环中运行良好。然而,我无法再次重申链表。(在bankers算法中,您可能只能运行链接列表中的最后一个。在这种情况下,您必须再次查看链接列表,看看是否还能运行(这是不起作用的部分)),我认为这与指针有关,但我不确定是什么C 重申链表(银行家算法),c,algorithm,linked-list,bankers-algorithm,C,Algorithm,Linked List,Bankers Algorithm,我正在做一个简单的银行家算法模拟器。当我将需求与可用资源进行比较时,它在1个循环中运行良好。然而,我无法再次重申链表。(在bankers算法中,您可能只能运行链接列表中的最后一个。在这种情况下,您必须再次查看链接列表,看看是否还能运行(这是不起作用的部分)),我认为这与指针有关,但我不确定是什么 struct LL //linked list structure(pcb) { LL_pid pid; int alloc[15]; int max[15]; int
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
};
这就是我被难倒的地方。我添加了一些测试printf,并意识到它不会重新迭代循环(可能是因为pcb_头的指针现在为空)
void makeBANK(PCB*PCB_头,int avail[15]){
PCB*温度=PCB_头;
国际可用新[15];
int x=0;
对于(x=0;xneed[i]){//如果可能,保留1,循环所有
可能=1;
}
否则{
可能=0;
printf(“oops”);
打破
}//如果不可能,请中断
}
如果(可能==1){//如果可能仍然为1,则打印
printf(“%d正在运行”,温度->pid);
温度->完成=1;
alldone++;
对于(z=0;zalloc[z];
printf(“avil:%d”,availnew[z]);
}
}
temp=temp->next;//并转到下一个节点(其他节点也需要)
}
}
如果(全部完成!=processCount)
printf(“不安全”);
其他的
printf(“safe”);
}
我愿意接受所有提示(组织..等),即使我在谷歌上找不到的简单解决方案中被否决。好吧,当while循环到达链表末尾(temp!=NULL)或当前进程被激活时,它需要终止 已完成(临时->完成=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;ifinish!=1){
//在此处检查资源可用性
如果(executionmable=1){//则可以执行进程
//在此处打印进程id
温度->完成=1;
//更新可用资源的数量
}
温度=温度->下一步;
}
}
我的解决方案(第二个):
for(i=0;i完成=1;
currentFinished=1;
//更新可用资源的数量
}
温度=温度->下一步;
}
}
PS:这是我关于堆栈溢出的第一个答案。欢迎反馈。1)
PCB
未定义2)[风格]在操作符周围使用一些空格。3) 诊断输出应转到stderr,而不是stdout 4)将“\n”
添加到诊断字符串5)[style]首选,用于(…)
循环而不是,而(…)
循环6)[style]尝试避免指示符变量(例如可能的);它们使程序流程复杂化。很酷,谢谢,我在struc:typedef int LL_pid;//之前有这些行PCB typedef struct LL PCB的pid//PCBI对它进行了一点调试,我认为它肯定与这一行有关:((temp!=NULL)&&(temp->finish!=1))如果头部在上一个循环中完成,它将无法再次循环。。现在来解决这个问题。如果您提出了解决方案,请让我知道。首先分析代码中会导致循环终止的行或会阻止执行代码的某些条件。快速浏览时,我会打印出“y”、“processCount”、“temp”(如果不为空)、“temp->finish”和“I”。此外,似乎您不需要定义“int i=0”,因为它仅用于“for(i=0…”循环中。“y”和“z”也是如此。此外,您为此编写了单元测试吗?谢谢!非常有意义!
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;
}
}