bobo bobo - 1 year ago 84
Python Question

Resource not releasing in Simpy - what am I doing wrong?

I have simplified the code representing the problem as suggested and attempted to debug.

Here is the most simple version of the code which still contains the bug:

import simpy


def source(env):
i = 0
while True:
i += 1
env.process(train(env, 'Train %d' % i, 'a'))
yield env.timeout(1)
i += 1
env.process(train(env, 'Train %d' % i, 'b'))
yield env.timeout(1)

def train(env, name, route):
resource_req = resource.request()
p3_req = p3.request()

if route == 'a':
print 'Route a %s generated' % name
yield resource_req
print 'Route a %s seized resource at time %d' % (name,
yield env.timeout(1)
print 'Route a %s released resource at time %d' % (name,

elif route == 'b':
print 'Route b %s generated' % name
yield p3_req
print 'Route b %s seized resource at time %d' % (name,
yield env.timeout(1)
print 'Route b %s released resource at time %d' % (name,

print 'Could not find a route branch'

env = simpy.Environment()

resource = simpy.Resource(env, 1)
p3 = simpy.Resource(env, 1)


The output from running this:

Route a Train 1 generated
Route a Train 1 seized resource at time 0
Route b Train 2 generated
Route a Train 1 released resource at time 1
Route a Train 3 generated
Route b Train 4 generated
Route a Train 5 generated

As you can see the resource is apparently released on "route a" but then no other resources can be seized either on route a or route b.

I'm very confused by this. Any help would be much appreciated!

Answer Source

Solved - there was a typo in the resource.

Originally defined as:

resource = simpy.Resource(env, 1)

Correct definition:

resource = simpy.Resource(env, capacity = 1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download