3

我目前正在使用 SimPy 对服务器进程进行建模和模拟,我希望该进程根据从何处接收到此消息来执行不同的操作。

SimPy 文档展示了如何等待多个事件:例如:yield event1 | 事件2

但是,我目前正在尝试等待多个商店提供资源。

场景如下: 服务器 S 正在等待来自各种渠道的消息。这些渠道中的每一个都可能具有不同的功能,这些功能会影响消息到达它所花费的时间。

这是有问题的代码:

resources = [inchannel.get() for inchannel in inchannels]
msg = yield simpy.events.AnyOf(env, resources)

其中 inchannel 是一个 Store 数组,用于对服务器的各种输入通道进行建模。

我遇到的问题是它似乎只接受来自其中一个频道的消息,无论它首先收到哪个频道。在它收到第一条消息后,它接受来自该通道的消息并忽略其他消息。

我还尝试了以下方法:

resource = inchannel[0].get() | inchannel[1].get() | ...
msg = yield resource

在这种情况下,它只接收来自 inchannel[0]

4

1 回答 1

3

您必须在每次迭代中创建一个新的 Get 事件列表。如果您重新使用旧列表,它仍将包含第一次迭代中触发的事件。

这应该有效:

inchannel = [simpy.Store(env) for i in range(3)]

while True:
    # Make a new list of Get events in each iteration
    events = [ic.get() for ic in inchannel]

    # Wait until (at least) one of them was triggered
    res = yield env.any_of(events)

    # Cancel all remaining requests, because you will make
    # new ones in the next iteration.
    # Do this *before* you yield anything
    [evt.cancel() for evt in evens]

    # Handle all messages (there *might* be more than one)
    for msg in res.values():
        handle_message(msg)
于 2015-05-01T07:23:06.473 回答