How can I have a process wait for multiple resources?

て烟熏妆下的殇ゞ 提交于 2021-02-07 19:53:26

问题


I am currently using SimPy to model and simulate a server process and I would like this process to execute a different action depending on where it receives this message from.

The SimPy documentation shows how to wait for multiple events: Ex: yield event1 | event2

However I am currently trying to wait for a resource to become available from multiple Stores.

The scenario is as follows: Server S is waiting for messages that can come from various channels. Each of these channels may have different features that affect the time it takes the message to reach it.

Here is the code in question:

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

where inchannel is an array of Stores that model the various channels of input into the server.

The issue I am having is that it only ever seems to accepts messages from one of the channels, whichever one it receives first. After it receives the first message, it accepts messages from that channel and ignores others.

I have also tried the following:

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

In this case it only receives from inchannel[0]


回答1:


You have to create a new list of Get events in each iteration. If your re-use the old list, it will still contain the triggered event from the first iteration.

This should work:

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)


来源:https://stackoverflow.com/questions/29976113/how-can-i-have-a-process-wait-for-multiple-resources

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!