In the following code snippet, I am trying to understand the simpy tutorial. I am unable to explain the output. I expect all the "\o/" to be printed in one go before other statements are printed. Also, there is a problem with the callback.
import simpy
class School:
def __init__(self, env):
self.env = env
self.class_ends = env.event()
self.pupil_procs = [env.process(self.pupil()) for i in range(3)]
for x in self.pupil_procs:
x.callbacks.append(self.my_callback(x))
#print(x.callbacks)
self.bell_proc = env.process(self.bell())
def bell(self):
for i in range(2):
value=yield self.env.timeout(45,value="bell_rang!at"+str(env.now))
self.class_ends.succeed(value='class_ends!')
print("in bell proc")
self.class_ends = self.env.event()
print(value)
def pupil(self):
for i in range(2):
print(' \o/',i, end=' ')
classends=yield self.class_ends
print('done!')
print(classends)
def my_callback(self,event):
print('Called back from',event)
env = simpy.Environment()
school = School(env)
env.run()
The output is as follows:
Called back from <Process(pupil) object at 0x7fd7ddce97b8>
Called back from <Process(pupil) object at 0x7fd7ddce9be0>
Called back from <Process(pupil) object at 0x7fd7ddcad5f8>
\o/ 0 \o/ 0 \o/ 0 in bell proc
bell_rang!at0
done!
class_ends!
\o/ 1 done!
class_ends!
\o/ 1 done!
class_ends!
\o/ 1 in bell proc
bell_rang!at45
done!
class_ends!
done!
class_ends!
done!
class_ends!
Traceback (most recent call last):
File "/home/deeplearning/PycharmProjects/python-scheduling/learnSimPy/learnmore.py", line 35, in <module>
env.run()
File "/usr/local/lib/python3.5/dist-packages/simpy/core.py", line 137, in run
self.step()
File "/usr/local/lib/python3.5/dist-packages/simpy/core.py", line 221, in step
callback(event)
TypeError: 'NoneType' object is not callable
Process finished with exit code 1
You add the result of self.my_callback(x)
(which is None
) to the list of callbacks.
Instead, you should append functools.partial(self.my_callback, x)
.
I also recommend that you rather use yield from process
instead of append functions to process
's callbacks.