异步队列的奇怪行为
Weird behaviour of asyncio Queue
为什么 asyncio 队列在这里表现得如此奇怪,即使在那里放了一个项目它也显示为空?
In [1]: from multiprocessing import Queue
In [2]: q = Queue()
In [3]: q.empty()
Out[3]: True
In [4]: q.put(100)
In [5]: q.empty()
Out[5]: False
In [6]: from asyncio import Queue
In [7]: q = Queue()
In [8]: q.empty()
Out[8]: True
In [9]: q.put(100)
Out[9]: <generator object Queue.put at 0x7f97849bafc0>
In [10]: q.empty()
Out[10]: True
因为你什么都没放:
q.put(100)
put
这里 - 不是一个简单的函数,它是一个 coroutine. You should await
它将项目放入队列。
例如:
import asyncio
from asyncio import Queue
async def main():
q = Queue()
print(q.empty()) # True
await q.put(100)
print(q.empty()) # False
if __name__ == '__main__':
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
作为 Mikhail Gerasimov 的回答,q.put(100)
是 coroutine
并解释更多细节...
Calling a coroutine does not start its code running – the coroutine
object returned by the call doesn’t do anything until you schedule its
execution. There are two basic ways to start it running: call await
coroutine or yield from coroutine from another coroutine (assuming the
other coroutine is already running!), or schedule its execution using
the ensure_future() function or the AbstractEventLoop.create_task()
method.
Coroutines (and tasks) can only run when the event loop is running.
在 Mikhail Gerasimov 的示例中,
另一个coroutine
async def main()
用coroutine
q.put(100)
调用await
,事件循环是运行loop.run_until_complete(main())
如上面的描述
为什么 asyncio 队列在这里表现得如此奇怪,即使在那里放了一个项目它也显示为空?
In [1]: from multiprocessing import Queue
In [2]: q = Queue()
In [3]: q.empty()
Out[3]: True
In [4]: q.put(100)
In [5]: q.empty()
Out[5]: False
In [6]: from asyncio import Queue
In [7]: q = Queue()
In [8]: q.empty()
Out[8]: True
In [9]: q.put(100)
Out[9]: <generator object Queue.put at 0x7f97849bafc0>
In [10]: q.empty()
Out[10]: True
因为你什么都没放:
q.put(100)
put
这里 - 不是一个简单的函数,它是一个 coroutine. You should await
它将项目放入队列。
例如:
import asyncio
from asyncio import Queue
async def main():
q = Queue()
print(q.empty()) # True
await q.put(100)
print(q.empty()) # False
if __name__ == '__main__':
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
作为 Mikhail Gerasimov 的回答,q.put(100)
是 coroutine
并解释更多细节...
Calling a coroutine does not start its code running – the coroutine object returned by the call doesn’t do anything until you schedule its execution. There are two basic ways to start it running: call await coroutine or yield from coroutine from another coroutine (assuming the other coroutine is already running!), or schedule its execution using the ensure_future() function or the AbstractEventLoop.create_task() method.
Coroutines (and tasks) can only run when the event loop is running.
在 Mikhail Gerasimov 的示例中,
另一个coroutine
async def main()
用coroutine
q.put(100)
调用await
,事件循环是运行loop.run_until_complete(main())
如上面的描述