Jiew Meng
Jiew Meng

Reputation: 88247

Loop not looping through all elements in list

I have

print(len(pcb.resources))
for res in pcb.resources:
    print ("Releasing resource: " + res.name)
    self.releaseResource(res.name, pcb)
print("After: " + str(len(pcb.resources)))

Which outputs

2 # from 1st print: this is correct, I have 2 elements in list
Releasing resource: R1 # is it not looping through the 2nd element? Notice the len() is 2
After: 1 # from print after loop. I am expecting 0

UPDATE

I notice its something to do with the function call. releaseResource. But how might releaseResource be affecting the calling loop?

def releaseResource(self, name, pcb = None):
    callScheduler = pcb is not None # if pcb is set, means calling from release resource, so dont call scheduler 1st

    if pcb is None:
        pcb = self.running

    # check if resource exists
    if not any(rcb.name == name for rcb in self.resources): 
        return False    
    rcb = next(r for r in self.resources if r.name == name)

    # remove resource from running pcb's resources
    pcb.resources.remove(rcb)

    if len(rcb.waitingList) == 0:
        # no waiting processes: resource is free
        rcb.status = RCB.STATUS_FREE
        rcb.heldBy = None
    else:
        # make dequeue from resource waiting list
        pcb = rcb.waitingList.popleft()

        # put resource into process resources list
        pcb.resources.append(rcb)
        rcb.heldBy = pcb

        # make it ready
        pcb.status = PCB.STATUS_READY
        pcb.statusList = self.readyList
        self.readyList.enqueue(pcb)

        # call scheduler
        if callScheduler:
            self.scheduler()

    return True

Upvotes: 0

Views: 1163

Answers (1)

stephan
stephan

Reputation: 10265

It looks to me like you modify the list in releaseResource you iterate over, namely in the line pcb.resources.remove(rcb). Try this instead:

for res in pcb.resources[:]:
    print ("Releasing resource: " + res.name)
    self.releaseResource(res.name, pcb)

See the documentation.

Upvotes: 4

Related Questions