是的
env.timeout 不会提前时钟。当代理调用 env.timeout 时,该代理会等到时钟到达该时间,它不会阻止其他代理执行操作。当第一个代理等待 env.timeout 完成时,其他代理仍然可以做事。
请注意,每个代理都需要使用 env.process 异步启动,而不是使用 yield
这是一个不太简单的例子
"""
agents calling each other in a agent base sim
Programmer Michael R. Gibbs
"""
import simpy
import random
class Agent():
"""
Agents do a background activity, and from time to time make a call to a friend agent
Agents wait to finish doing stuff, then call back the calling friend agent
"""
def __init__(self, env, agent_id):
"""
set up agent
Need to set the friend later since that agent may not have been created yet
"""
self.env = env
self.agent_id = agent_id
self.friend = None # set this before starting sim
self.friend_called = None
# kick off background activity, and activty that makes calls from time to time
env.process(self.agent_stuff())
env.process(self.make_call())
def receive_call(self, agent):
"""
agent is busy, will call back later
"""
# save caller for later callback
self.friend_called = agent
print(f"{self.env.now} agent {self.agent_id} just got a call from agent {agent.agent_id}")
def receive_callback(self, agent):
"""
getting a call from the agent this agent called ealier
"""
print(f"{self.env.now} agent {self.agent_id} just got a callback from agent {agent.agent_id}")
def make_call(self):
"""
loop making calls from time to time
"""
while True:
yield self.env.timeout(random.randint(4,9))
self.friend.receive_call(self)
print(f"{self.env.now} agent {self.agent_id} just made a call to agent {self.friend.agent_id}")
def agent_stuff(self):
"""
agent process doing agent stuff
"""
while True:
t = random.randint(1,5)
print(f"{self.env.now} agent {self.agent_id} will do his thing in {t}")
yield env.timeout(t)
print(f"{self.env.now} agent {self.agent_id} is doing his thing")
if self.friend_called is not None:
# oh look, someone called, call them back
self.friend_called.receive_callback(self)
print(f"{self.env.now} agent {self.agent_id} just made a call to agent {self.friend.agent_id}")
self.friend_called = None
env = simpy.Environment()
# create agents, which also starts their processes
agent1 = Agent(env,1)
agent2 = Agent(env,2)
# set the friend
agent1.friend = agent2
agent2.friend = agent1
env.run(100)