Simpy - 何时使用yield以及何时调用该函数

时间:2017-03-22 15:33:07

标签: python simpy

我正在尝试使用Simpy模拟城市网格周围移动汽车的一些行为。但是,我在概念上围绕何时使用像

这样的东西时遇到了一些麻烦

yield self.env.timeout(delay)yield env.process(self.someMethod()) 而只是调用方法self.someMethod()

在非常理论的层面上,我理解yield语句和生成器,了解它们如何应用于迭代,但不太确定它与Simpy的关系。

Simpy教程仍然非常密集。

例如:

class Car(object):
    def __init__(self, env, somestuff):
        self.env = env
        self.somestuff = somestuff

        self.action = env.process(self.startEngine())  # why is this needed?  why not just call startEngine()?

    def startEngine(self):
        #start engine here
        yield self.env.timeout(5) # wait 5 seconds before starting engine
        # why is this needed?  Why not just use sleep? 



env = simpy.Environment()
somestuff = "blah"
car = Car(env, somestuff)
env.run()

1 个答案:

答案 0 :(得分:2)

看起来你并没有完全理解generator / async 功能呢。我在下面评论你的代码并希望它有所帮助 你要明白发生了什么:

import simpy

class Car(object):
    def __init__(self, env, somestuff):
        self.env = env
        self.somestuff = somestuff

        # self.startEngine() would just create a Python generator
        # object that does nothing.  We must call "next(generator)"
        # to run the gen. function's code until the first "yield"
        # statement.
        #
        # If we pass the generator to "env.process()", SimPy will
        # add it to its event queue actually run the generator.
        self.action = env.process(self.startEngine()) 

    def startEngine(self):
        # "env.timeout()" returns a TimeOut event.  If you don't use
        # "yield", "startEngine()" returns directly after creating
        # the event.
        #
        # If you yield the event, "startEngine()" will wait until
        # the event has actually happend after 5 simulation steps.
        # 
        # The difference to time.sleep(5) is, that this function
        # would block until 5 seconds of real time has passed.
        # If you instead "yield event", the yielding process will
        # not block the whole thread but gets suspend by our event
        # loop and resumed once the event has happend.
        yield self.env.timeout(5)


env = simpy.Environment()
somestuff = "blah"
car = Car(env, somestuff)
env.run()