【问题标题】:Simpy - when to use yield and when to call the functionSimpy - 何时使用 yield 以及何时调用函数
【发布时间】:2017-03-22 15:33:06
【问题描述】:

我正在尝试使用 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()

【问题讨论】:

  • Python 中的注释以# 开头,而不是//
  • 糟糕,谢谢。在将代码粘贴到 SO 后,我添加了该评论。

标签: python simpy


【解决方案1】:

您似乎没有完全理解生成器/异步 功能呢。我在下面评论您的代码,希望对您有所帮助 您了解正在发生的事情:

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()

【讨论】:

  • 这对我有帮助。谢谢!
猜你喜欢
  • 2012-01-07
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 2015-08-08
  • 2014-02-16
相关资源
最近更新 更多