我正在使用 simpy 进行机器人模拟,我开始使用两个称为 ping 和 pong 的球拍编写一个简单的乒乓球游戏。只有当我添加 ayield env.timeout(0)
以让一个玩家为对方玩家提供轮到他的机会时,它才能正常工作。如果我跳过这个 noop(?),第一个球员一直抓住球。这是我的代码:
import simpy
ball_wait = 1
def racket(env, name, ball):
while True:
# Let the first user catch the ball
with ball.request() as req: # Create a waiting resource
yield req # Wait and get the ball
# The time it takes for the ball to arrive. This can
# be used to plan the strategy of how to hit the ball.
yield env.timeout(ball_wait)
print env.now, name
# "Sleep" to get the other user have his turn.
yield env.timeout(0)
env = simpy.Environment()
ball = simpy.Resource(env, capacity = 1)
env.process(racket(env, 'Ping', ball))
env.process(racket(env, 'Pong', ball))
env.run(until=10)
print 'Done!'
我的问题是为什么我需要env.timeout(0)
? 我还想知道是否还有其他一些(更好的?)在两个进程之间移交控制权的策略?我也玩过,process.interrupt()
但在我看来这有点矫枉过正。