此代码
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))
产生此输出:
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
为什么队列变空,即使我没有yield from
并且流量控制没有返回循环?我希望,元素不会弹出"弹出"从队列直到我将流量控制返回到循环,它决定" pop"数据
答案 0 :(得分:3)
在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())
我们可以看到,如果未满足至少一个get()
,则对put_nowait()
的任何调用都会将一个项目放入队列,然后立即弹出 ,没有机会让队列处于非空状态。