3

我正在尝试将 SimPy 模拟添加到我正在处理的项目中,但我对版本 3 的发布/请求有些困惑。

我能够使用“with”块毫无问题地实现资源,但在我的情况下,我想在不使用“with”块的情况下请求/释放资源。

但是,我找不到使用 SimPy 3 的示例。我阅读了有关资源的文档/源代码,但仍然不能完全正确。有人可以解释如何正确地:

...
Request a Resource with the method: 'request()'
...
Release that Resource with the method: 'release()'
...

谢谢,很抱歉打扰。

PS:我打算使用 Resources.resource

4

3 回答 3

5

如果你想使用没有with阻塞的资源(并且你知道你不会被打断),它只是:

req = resource.request()
yield req
# do stuff
resource.release(req)
于 2014-05-19T07:03:06.287 回答
3

在您进入块和离开时with调用对象上的使用。所以当你这样做时__enter__with__exit__

res = resource.Resource()
with res.request() as req:
  # stuff

你真的__enter__在调用一个 Request 对象,#stuff然后调用__exit__

class Request(base.Put):
    def __exit__(self, exc_type, value, traceback):
        super(Request, self).__exit__(exc_type, value, traceback)
        self.resource.release(self)

class Put(Event):  # base.Put
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        # If the request has been interrupted, remove it from the queue:
        if not self.triggered:
            self.resource.put_queue.remove(self)

因此,该with块等价于:

res = resource.Resource(...)
req = res.request()
#stuff
if not req.triggered:
   res.put_queue.remove(req)
   res.release(req)

但是,该with块还确保无论在#stuff. 使用上面的代码你会失去它。

于 2014-05-18T22:51:04.907 回答
0

这一切都在PEP343中概述;

with EXPR as VAR:
        BLOCK

变成:

mgr = (EXPR)
exit = type(mgr).__exit__  # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
    try:
        VAR = value  # Only if "as VAR" is present
        BLOCK
    except:
        # The exceptional case is handled here
        exc = False
        if not exit(mgr, *sys.exc_info()):
            raise
        # The exception is swallowed if exit() returns true
finally:
    # The normal and non-local-goto cases are handled here
    if exc:
        exit(mgr, None, None, None)

正是python 使用with... as...块的方式,但我假设你不想使用这些是有原因的。如果是这种情况,那么您只需要__enter__and__exit__函数。我认为它的方式是__enter__设置一切,__exit__并进行所有清理。

于 2014-05-18T22:55:04.127 回答