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

标签 python simpy

我正在尝试使用 Simpy 来模拟在城市网格中移动汽车的一些行为。然而,我在概念上遇到了一些困难,什么时候使用类似

yield self.env.timeout(delay)yield env.process(self.someMethod()) 与仅调用方法 self.someMethod() 相比。

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

Simply 教程仍然相当密集。

例如:

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

最佳答案

看来您没有完全理解生成器/异步 功能还没有。我在下面评论您的代码并希望它有所帮助 您了解发生了什么:

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

关于python - Simpy - 何时使用yield以及何时调用该函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42956208/

相关文章:

Python Pandas - 处理具有嵌套字典(json)值的列

python - 有没有办法根据 pandas DataFrame 中的类别查找模式?

python - VIM + netrw : open multiple files/buffers in the same window

python - 按列任意排序矩阵

python - 尝试在 python 中使用正则表达式

python - 我可以并行运行两个 Simpy 环境吗

python - 过滤器存储队列

python - 简单地获取正在等待资源空闲的元素