【问题标题】:What is non-blocking generator什么是非阻塞生成器
【发布时间】:2014-12-21 11:54:24
【问题描述】:

这段摘自 Python doc。它的文档字符串说函数是non-blocking(例如# non-blocking dict iterator),这就是我不明白的地方。

def iter_except(func, exception, first=None):
    """ Call a function repeatedly until an exception is raised.

    Converts a call-until-exception interface to an iterator interface.
    Like builtins.iter(func, sentinel) but uses an exception instead
    of a sentinel to end the loop.

    Examples:
        iter_except(functools.partial(heappop, h), IndexError)   # priority queue iterator
        iter_except(d.popitem, KeyError)                         # non-blocking dict iterator
        iter_except(d.popleft, IndexError)                       # non-blocking deque iterator
        iter_except(q.get_nowait, Queue.Empty)                   # loop over a producer Queue
        iter_except(s.pop, KeyError)                             # non-blocking set iterator

    """
    try:
        if first is not None:
            yield first()            # For database APIs needing an initial cast to db.first()
        while 1:
            yield func()
    except exception:
        pass

在我看来,generator functioniter() 做同样的事情。

据我所知,non-blocking 表示异步或并行计算,或者当您在 multi-thread 中摆脱 lock 时。 sn-p 处于同步执行状态。 non-blocking 这里是什么意思?

【问题讨论】:

  • 我想他们的意思是 d 可以在迭代期间被其他代码更改,所以这个函数不会“阻止”它。使用iter 和更改底层容器可能会导致不可预知的结果。

标签: python generator nonblocking coroutine


【解决方案1】:

据我了解 - 这里的non-blocking 用作not breaking the code execution when a specific error occurs

因此,当异常发生时,这些生成器不会“阻止”我的代码运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 2012-10-31
    • 2012-06-13
    • 2020-05-22
    • 1970-01-01
    相关资源
    最近更新 更多