1
我正在使用python和simpy進行仿真。在模擬中,一個實例(中斷)可以被另一箇中斷(中斷者)中斷。我爲每個中斷使用嵌套嘗試除外語句。如果我知道中斷的最大數量,嵌套嘗試除了語句工作。Simpy;如何合併未知數量的中斷
問題是我不知道會發生多少次中斷(可能是1,2,3,...)。我不知道如何處理一箇中斷未知次數的物體。
下面的代碼適用於三個中斷,但是如果包含第四個中斷(由於三個嵌套嘗試除外語句)會中斷。
是否有可能使代碼更通用,因此它可以處理未知數量的中斷?
任何幫助,非常感謝。
代碼:使用
uninterrupted at 0
first interrupt
interrupted at 1
second interrupt
interrupted at 2
third interrupt
interrupted at 3
Traceback (most recent call last):
File "interrupt.py", line 58, in <module>
env.run(until=15)
File "/usr/local/lib/python2.7/dist-packages/simpy/core.py", line 137, in run
self.step()
File "/usr/local/lib/python2.7/dist-packages/simpy/core.py", line 229, in step
raise exc
simpy.events.Interrupt: Interrupt('fourth interrupt')
版本::
import simpy
import random
class Interupted(object):
def __init__(self, env):
self.env = env
self.isInterrupted = False
self.action = env.process(self.run())
def run(self):
self.isInterrupted = False
try:
print('uninterrupted at %s' % (self.env.now))
yield self.env.timeout(3)
except simpy.Interrupt as interrupt:
print(interrupt.cause)
try:
self.isInterrupted = True
print('interrupted at %s' % (self.env.now))
yield self.env.timeout(10)
except simpy.Interrupt as interrupt:
print(interrupt.cause)
try:
self.isInterrupted = True
print('interrupted at %s' % (self.env.now))
yield self.env.timeout(10)
except simpy.Interrupt as interrupt:
print(interrupt.cause)
self.isInterrupted = True
print('interrupted at %s' % (self.env.now))
yield self.env.timeout(10)
class Interruptor(object):
def __init__(self, env, interrupted):
self.env = env
self.interrupted = interrupted
self.action = env.process(self.run(interrupted))
def run(self, interrupted):
yield self.env.timeout(1)
interrupted.action.interrupt("first interrupt")
yield self.env.timeout(1)
interrupted.action.interrupt("second interrupt")
yield self.env.timeout(1)
interrupted.action.interrupt("third interrupt")
yield self.env.timeout(1)
interrupted.action.interrupt("fourth interrupt")
env = simpy.Environment()
interrupted = Interupted(env)
interruptor = Interruptor(env, interrupted)
env.run(until=15)
輸出
- 的Python:2.7.3
- 的simpy:3.0.7