[英]asyncio.queue strange behaviour
This code 这段代码
import asyncio
@asyncio.coroutine
def foo(q):
print("foo before", q.empty())
q.put_nowait("yoba")
print("foo after", q.empty())
@asyncio.coroutine
def bar(q):
for _ in range(5):
asyncio.async(foo(q))
r = yield from q.get()
print("bar received", r)
q = asyncio.Queue()
asyncio.get_event_loop().run_until_complete(bar(q))
Produce this output: 产生这个输出:
foo before True
foo after True
bar received yoba
foo before True
foo after True
bar received yoba
foo before True
foo after True
bar received yoba
foo before True
foo after True
bar received yoba
foo before True
foo after True
bar received yoba
Why queue become empty, even when I did not yield from
and flow control did not return to loop? 为什么队列变空,即使我没有
yield from
并且流量控制没有返回循环? I expect, that elements will not "pop" from queue until I will return flow control to loop and it decide to "pop" data. 我希望,元素不会从队列中“弹出”,直到我将流控制返回到循环并且它决定“弹出”数据。
In the source of asyncio.Queue.put_nowait
: 在
asyncio.Queue.put_nowait
的源代码中:
if self._getters:
assert not self._queue, (
'queue non-empty, why are getters waiting?')
getter = self._getters.popleft()
self.__put_internal(item)
# getter cannot be cancelled, we just removed done getters
getter.set_result(self._get())
As we can see, if at least one get()
is not fulfilled, any call to put_nowait()
will put an item into the queue, then pop it immediately , giving no chance for the queue to be in a nonempty state. 正如我们所看到的,如果至少有一个
get()
未满足,则对put_nowait()
任何调用都会将一个项放入队列,然后立即弹出,不会让队列处于非空状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.