"""
Simple demo on how to handel process interrupts
Programmer: Michael R. Gibbs
"""
from re import I
import simpy
def the_process(env):
"""
simple process that will get interrupted
"""
i_cnt = 0 # count the number of interuptions
not_done = True # flags when done
# event that process yields to
the_event = env.timeout(15)
print(f'{env.now:0.2f} the process has started')
# loop until done
while not_done:
try:
yield the_event
except simpy.Interrupt as i:
# have been interupted
i_cnt += 1
print(f'{env.now:0.2f} the process has been intrruped {i_cnt} times {i.cause}')
# there are several ways you can process the interupt
if i_cnt == 1:
# process the error and resume
# the loop will yield to the same event as before, not a new event
# because the interupt does not end other events, even events
# created by this process
print(f'{env.now:0.2f} the process handeled the intrupt and resumed')
elif i_cnt == 2:
# process the error and exit the process
# by stopping the loop
not_done = False
print(f'{env.now:0.2f} the process handeled the intrupt and is stopping')
# third option is to rethrow the interupt and let a parrent process deal with it
print(f'{env.now:0.2f} the process has ended')
def the_interrupter(env, the_process):
"""
interupts a process two time
"""
yield env.timeout(5)
print(f'{env.now:0.2f} sending first interrupt')
the_process.interrupt("first interrupt")
yield env.timeout(5)
print(f'{env.now:0.2f} sending second interrupt')
the_process.interrupt("second interrupt")
env = simpy.Environment()
process1 = env.process(the_process(env))
env.process(the_interrupter(env, process1))
env.run(100)