我一遍又一遍地阅读“Luciano Ramalho”的“Fluent Python”,但我无法理解 asyncio.sleep 在 asyncio 中的行为。
书中有一部分说:
Never use time.sleep in asyncio coroutines unless you want to block the main thread, therefore freezing the event loop and probably the whole application as well. (...) it should yield from asyncio.sleep(DELAY).
另一方面:
Every Blocking I/O function in the Python standard library releases the GIL (...) The time.sleep() function also releases the GIL.
随着 time.sleep() 的发布,其他线程上的 GIL 代码可以运行,但会阻塞当前线程。由于 asyncio 是单线程的,我知道 time.sleep 会阻塞 asyncio 循环。
但是, asyncio.sleep() 如何不阻塞线程?是否可以不延迟事件循环并同时等待?
最佳答案
在引擎盖下,asyncio
有一个“事件循环”:它是一个循环任务队列的函数。当您添加新任务时,它会添加到队列中。当任务产生时,它被挂起并且事件循环移动到下一个任务。暂停的任务将被忽略,直到它们恢复。当任务完成时,它会从队列中移除。
例如,当您调用 asyncio.run
,它将新任务添加到队列中,然后进入事件循环,直到没有更多任务为止。
官方文档中的一些引用:
The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses.
Event loops use cooperative scheduling: an event loop runs one Task at a time. While a Task awaits for the completion of a Future, the event loop runs other Tasks, callbacks, or performs IO operations.
当您调用
asyncio.sleep
,它暂停当前任务,从而允许其他任务运行。好吧,我基本上是在复述 documentation :sleep() always suspends the current task, allowing other tasks to run.
关于python - asyncio.sleep 如何不阻塞线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62493718/