【发布时间】:2021-02-09 10:58:15
【问题描述】:
我正在使用 Simpy 4,但不知道如何同时安排多个事件。
例如,假设一条起跑线上有 3 辆汽车,我希望它们都同时开始。例如,下面的代码不能按我的意愿工作,因为每个“移动”一个接一个地发生,而不是同时发生。
import simpy
from itertools import cycle
class Dispatch():
def __init__(self, env, cars):
self.cars = cars
self.action = env.process(self.run())
def run(self):
while True:
for car in self.cars:
yield env.process(car.move())
class Car():
def __init__(self, env, name, initial_location):
self.env = env
self.name = name
self.location = initial_location
self.path = iter(cycle(["A", "B", "C", "B"]))
def move(self):
yield env.timeout(1)
self.location = next(self.path)
print("{} is now at position {}, at time: {}".format(self.name, self.location, env.now))
env = simpy.Environment()
carA = Car(env, "carA", "A")
carB = Car(env, "carB", "A")
carC = Car(env, "carC", "A")
dispatcher = Dispatch(env, [carA,carB,carC])
env.run(until=20)
现在因为每辆车都是按顺序启动的,所以结果如下:
carA is now at position A, at time: 1
carB is now at position A, at time: 2
carC is now at position A, at time: 3
carA is now at position B, at time: 4
carB is now at position B, at time: 5
carC is now at position B, at time: 6
carA is now at position C, at time: 7
carB is now at position C, at time: 8
carC is now at position C, at time: 9
但我想要的是:
carA is now at position A, at time: 1
carB is now at position A, at time: 1
carC is now at position A, at time: 1
carA is now at position B, at time: 2
carB is now at position B, at time: 2
carC is now at position B, at time: 2
carA is now at position C, at time: 3
carB is now at position C, at time: 3
carC is now at position C, at time: 3
所以我想我正在寻找一种方法来重写 for 循环。
最终会有多辆汽车(如上例所示),我想分别控制每辆汽车。但我想作为一个起点,最好知道如何将每个汽车事件添加到事件列表中,以便它们同时开始。
有什么帮助吗?谢谢:)
最好的问候
编辑
好的,我不会把它作为答案写下来,因为我并不完全理解它。但我有我想要的结果。我创建了多个 Dispatch 对象,并分别运行每个对象。除非其他人能清楚地解释这一点,否则我会等我弄清楚后再发布答案。
class Dispatch():
def __init__(self, env, car):
self.car = car
self.action = env.process(self.run())
def run(self):
while True:
yield env.process(self.car.moveto())
class Car():
def __init__(self, env, name, initial_location):
self.env = env
self.name = name
self.location = initial_location
self.path = cycle(["A", "B", "C", "B"])
def moveto(self):
if self.name == "carA":
yield env.timeout(1)
elif self.name == "carB":
yield env.timeout(4)
self.location = next(self.path)
print("{} is now at node: {}, at time: {}".format(self.name, self.location, env.now))
env = simpy.Environment()
carA = Car(env, "carA", "A")
carB = Car(env, "carB", "A")
cars = [carA, carB]
for car in cars:
Dispatch(env, car)
env.run(until=20)
【问题讨论】: