I have a basic question that I don’t seem to be able to find the answer to. I just want to pass a variable from a process to another, but I read that I shouldn’t use a return statement to do so, because that can terminate a running process in a while loop. I have the following code:
import simpy as sp
def my_proc(env):
while True:
yield env.timeout(2)
return env.now
def other_proc(env):
while True:
ret_val = yield env.process(my_proc(env))
print(env.now,ret_val)
env=sp.Environment()
env.process(my_proc(env))
env.process(other_proc(env))
env.run(until=10)
And it seems to run properly printing 2 2, 4 4 , 6 6 … I expected it to not work because the return statement is there, but instead it works properly. Is this the proper way to pass a value from a process to another? Is this the recommended way?
Your code has some useless statements. Look:
Way 1
The corrected code looks like this
and still works as you expect.
Way 2
Probably, in some of your real programs the analog of
my_proc
can contain a lot of heavy logic before the infinite loop, for example. So you do not want to create this process in each iteration inother_proc
. You are forced to provide communication between processes. In such case you can use the shared resource (see more in Shared Resources).In your case the simpy.Store resource is appropriate:
Way 3
Moreover, there is another way. You can use a shared event but this requires some shared event variable. This is easy to do using a class (or a global variable but this is not recommended):