I'm trying to interrupt a set of nested processes in simpy. It appears from the following code that only the first layer of processes is interrupted by an interrupt event, and I can't seem to find a way to reference the processes defined within another process from outside the outer process in order to interrupt them. Below is a minimum reproducible example:
import simpy
env = simpy.Environment()
def process_one():
try:
yield env.timeout(5)
print("inside process one")
yield env.process(process_two())
yield env.timeout(10)
except simpy.Interrupt:
print("interrupted at ", env.now)
def process_two():
try:
yield env.timeout(5)
print("inside process two")
yield env.timeout(5)
print("finishing process two")
except simpy.Interrupt:
print("process two interrupted at", env.now)
process = env.process(process_one())
def interruption(time):
yield env.timeout(time)
process.interrupt()
env.process(interruption(6))
env.run(until=30)
Process one gets interrupted as it should, but process two continues on its business. If I assign env.process(process_two)
to a variable inside process_one
, I can't access it from outside the scope of process_one
. Is there a way to cause an interruption to interrupt all ongoing processes defined within a parent process, or do all processes in simpy have to be defined only one layer deep?
Only the process on which you call interrupt()
gets interrupted. To interrupt the second process, you need a reference to it:
If you want to interrupt the currently active process, use Environment.active_process to get a ref to it.
If you want to explicitly interrupt the second process, store a ref to it somewhere in a shated namespace.
Finally, you can also catch the interrupt in process one and forward it to process two. Process one can than continue to work (if it wants to).