python - asyncio.sleep 如何不阻塞线程?

标签 python multithreading gil

我一遍又一遍地阅读“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 ,它将新任务添加到队列中,然后进入事件循环,直到没有更多任务为止。
官方文档中的一些引用:

  • Event Loop

  • The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses.


  • Task

  • 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/

    相关文章:

    python - 将 Twitter Bootstrap 轻松集成到任何 Pyramid 表单框架

    python - 两个 DataFrame 的复杂合并

    ruby - 我如何管理 ruby​​ 线程以便它们完成所有工作?

    c# - 来自多个线程的安慰 session SendRequest() 正在阻塞

    java - 使用 ThreadPoolExecutor 的 CPU 性能

    python - 使用 Py_BEGIN_ALLOW_THREADS 时如何避免 Python C 扩展中的 gcc 警告

    python - pydoc 生成带有文件句柄参数的帮助文本

    Python unhashable type dict 关于为什么这两种方法有不同结果的问题

    python - concurrent.futures 是 GIL 的良药吗?

    python - 解释性语言如何避免使用全局解释器锁(GIL)?