Простой приоритет для поломки/ремонта нескольких экземпляров

Я экспериментировал с примером разбивки шины в руководстве Simpy и действительно изо всех сил пытаюсь понять, почему, когда я создаю несколько экземпляров шины, последний экземпляр, кажется, получает «последовательность» после первого ремонта. Я немного изменил пример кода в руководстве сразу после оператора initialize(), чтобы создать два экземпляра Bus (Bus1 и Bus2). Вот мой код:

from SimPy.Simulation import *

class Bus(Process):

  def operate(self,repairduration,triplength):    # PEM
     tripleft = triplength
        # "tripleft" is the driving time to finish trip
        # if there are no further breakdowns
     while tripleft > 0:
        yield hold,self,tripleft      # try to finish the trip
            # if a breakdown intervenes
        if self.interrupted():
              print self.interruptCause.name, 'at %s' %now()
              tripleft=self.interruptLeft
                # update driving time to finish
                # the trip if no more breakdowns
              self.interruptReset()        # end self-interrupted state
                # update next breakdown time
              reactivate(br,delay=repairduration)
                # impose delay for repairs on self
              yield hold,self,repairduration
              print '%s repaired at %s' %(self.name, now())
        else:   # no breakdowns intervened, so bus finished trip
              break
     print 'Bus has arrived at %s' %now()

class Breakdown(Process):
   def __init__(self,myBus):
       Process.__init__(self,name='Breakdown '+myBus.name)
       self.bus=myBus

   def breakBus(self,interval):      # Process Execution Method
       while True:
          yield hold,self,interval   # driving time between breakdowns
          if self.bus.terminated(): break
            # signal "self.bus" to break itself down
          self.interrupt(self.bus)

initialize()
for i in range(1,5):
  b=Bus('Bus%s' %i)                   # create a Bus object "b" called "Bus"
  activate(b,b.operate(repairduration=20,triplength=1000))
      # create a Breakdown object "br" for bus "b", and
  br=Breakdown(b)
      # activate it with driving time between
      # breakdowns equal to 300
  activate(br,br.breakBus(300))

simulate(until=4000)
print 'SimPy: No more events at time %s' %now()

Приведенное выше дает следующий результат:

Breakdown Bus1 at 300
Breakdown Bus2 at 300
Bus1 repaired at 320
Bus2 repaired at 320
Breakdown Bus1 at 600
Bus1 repaired at 620
Breakdown Bus2 at 620
Bus2 repaired at 640
Breakdown Bus1 at 900
Bus1 repaired at 920
Breakdown Bus2 at 920
Bus2 repaired at 940
Bus has arrived at 1060
Bus has arrived at 1060
SimPy: No more events at time 1240

Теперь вопрос: почему в момент t=600 автобус 1 ремонтируется раньше, чем автобус 2 выходит из строя? Я ожидал, что оба автобуса сломаются и будут отремонтированы «на ходу». Кроме того, если я создам четыре шины, первые три выйдут из строя и будут восстановлены на «этапе блокировки», как показано ниже; однако Автобус 4 выходит из строя на 20 после первого ремонта. Я не могу понять, почему это происходит, и был бы признателен за любое понимание, которое кто-либо мог бы предоставить. Это всегда происходит до последней инстанции.

Breakdown Bus1 at 300
Breakdown Bus2 at 300
Breakdown Bus3 at 300
Breakdown Bus4 at 300
Bus1 repaired at 320
Bus2 repaired at 320
Bus3 repaired at 320
Bus4 repaired at 320
Breakdown Bus1 at 600
Breakdown Bus2 at 600
Breakdown Bus3 at 600
Bus1 repaired at 620
Bus2 repaired at 620
Bus3 repaired at 620
Breakdown Bus4 at 620
Bus4 repaired at 640
Breakdown Bus1 at 900
Breakdown Bus2 at 900
Breakdown Bus3 at 900
Bus1 repaired at 920
Bus2 repaired at 920
Bus3 repaired at 920
Breakdown Bus4 at 920
Bus4 repaired at 940
Bus has arrived at 1060
Bus has arrived at 1060
Bus has arrived at 1060
Bus has arrived at 1060
SimPy: No more events at time 1240

Спасибо, Сеймур


person Seymour Morris    schedule 16.05.2012    source источник


Ответы (1)


Кажется, это работает так, как ожидалось. Процесс разбивки должен быть инициализирован и активирован в классе Bus.

from SimPy.Simulation import *

class Bus(Process):

  def __init__(self,name):
    Process.__init__(self,name)
    self.name = name
    self.br=Breakdown(self)
    activate(self.br,self.br.breakBus(300))


  def operate(self,repairduration,triplength):    # PEM
     tripleft = triplength
     while tripleft > 0:
        yield hold,self,tripleft      # try to finish the trip
        if self.interrupted():
              print self.interruptCause.name, 'at %s' %now()
              tripleft=self.interruptLeft
              self.interruptReset()        # end self-interrupted state
                # update next breakdown time
              reactivate(self.br,delay=repairduration)
              yield hold,self,repairduration
              print '%s repaired at %s' %(self.name, now())
        else:   # no breakdowns intervened, so bus finished trip
              break
     print 'Bus has arrived at %s' %now()

class Breakdown(Process):
   def __init__(self,myBus):
       Process.__init__(self,name='Breakdown '+myBus.name)
       self.bus=myBus

   def breakBus(self,interval):      # Process Execution Method
       while True:
          yield hold,self,interval   # driving time between breakdowns
          if self.bus.terminated(): break
            # signal "self.bus" to break itself down
          self.interrupt(self.bus)

initialize()

for i in range(1,5):
  b=Bus('Bus%s' %i)
  activate(b,b.operate(repairduration=20,triplength=1000))



simulate(until=4000)
print 'SimPy: No more events at time %s' %now()

Это приводит к тому, что четыре экземпляра Bus ломаются одновременно и ремонтируются одновременно, как показано в следующем выводе:

Breakdown Bus1 at 300
Breakdown Bus2 at 300
Breakdown Bus3 at 300
Breakdown Bus4 at 300
Bus1 repaired at 320
Bus2 repaired at 320 
Bus3 repaired at 320
Bus4 repaired at 320
Breakdown Bus1 at 600
Breakdown Bus2 at 600
Breakdown Bus3 at 600
Breakdown Bus4 at 600
Bus1 repaired at 620
Bus2 repaired at 620
Bus3 repaired at 620
Bus4 repaired at 620
Breakdown Bus1 at 900
Breakdown Bus2 at 900
Breakdown Bus3 at 900
Breakdown Bus4 at 900
Bus1 repaired at 920
Bus2 repaired at 920
Bus3 repaired at 920
Bus4 repaired at 920
Bus has arrived at 1060
Bus has arrived at 1060
Bus has arrived at 1060
Bus has arrived at 1060
SimPy: No more events at time 1200
person Seymour Morris    schedule 17.05.2012