问题
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