首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Simpy -何时使用产额和何时调用函数

Simpy -何时使用产额和何时调用函数
EN

Stack Overflow用户
提问于 2017-03-22 15:33:06
回答 1查看 2.6K关注 0票数 1

我试图用Simpy来模拟一些在城市电网中移动汽车的行为。然而,我在概念上遇到了一些问题,我想什么时候应该使用这样的东西

yield self.env.timeout(delay)yield env.process(self.someMethod())相对于只调用self.someMethod()方法而言。

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

Simpy教程仍然相当密集。

例如:

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-23 08:51:31

看起来您还没有完全理解生成器/异步函数。我在下面对您的代码进行评论,希望它能帮助您了解正在发生的事情:

代码语言:javascript
复制
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()
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42956208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档