I am making a simple bankers algorithm simulator. When I compare the need with the available resources it works fine for 1 loop. However I cannot get it to reiterate the linked list again. (In bankers algorithm you may only be able to run the last in the linked list. In that case you would have to go through the linked list again to see if anymore can run[this is the part that is not working])I think it has something to do with the pointers, but I'm not sure what.
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
};
Heres where I am stumped. I added some test printfs and realized that it does not re iterate the loop(probably since the pointer of pcb_head is now 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");
}
I am open to all tips(organization..etc) even if I get downvoted for a possibly simple solution I could not find on google.
All right, the while loop needs to terminate when either it has reached end of linked list (temp != NULL) or when the current process is finished (temp -> finish = 1).
Problem is what if there is a process in linked list which has already finished?
I can suggest two solutions:
this is demo code for the situation we have :
current condition:
My Solution(second one) :
PS : This is my first answer on stack overflow. Feedback are welcome.