了解异步已在运行的永久循环和挂起任务

2022-03-25 00:00:00 python python-asyncio

问题描述

我在理解如何将新任务挂起到已在运行的事件循环时遇到问题。

此代码:

import asyncio
import logging

@asyncio.coroutine
def blocking(cmd):
    while True:
        logging.info("in blocking coroutine")
        yield from asyncio.sleep(0.01)
        print("ping")

def main():
    logging.info("in main funciton")
    loop = asyncio.get_event_loop()
    logging.info("new loop created")
    logging.info("loop running forever")
    loop.run_forever()
    asyncio.async(blocking("ls"))

logging.basicConfig(level = logging.INFO)
main()

run_forever()更改为run_until_complete(asyncio.async(blocking("ls"))可以正常工作。但我真的很困惑-为什么我不能在已经运行的循环上挂起任务?


解决方案

问题是对loop.run_forever()的调用阻塞;它启动事件循环,直到您显式停止该循环才会返回-因此forever部分。您的程序从不显式停止事件循环,因此您的asyncio.async(blocking("ls"))调用永远不会到达。

使用asyncio.async将新任务添加到已在运行的循环中很好,您只需确保该函数实际上是从事件循环内的协程或回调中调用的。以下是一些示例:

安排blocking在事件循环启动后立即运行:

def main():
    logging.info("in main funciton")
    loop = asyncio.get_event_loop()
    logging.info("new loop created")
    logging.info("loop running forever")
    asyncio.async(blocking("ls"))
    loop.run_forever()

从事件循环执行的回调中调度blocking

def start_blocking():
    asyncio.async(blocking("ls"))

def main():
    logging.info("in main funciton")
    loop = asyncio.get_event_loop()
    logging.info("new loop created")
    logging.info("loop running forever")
    loop.call_soon(start_blocking)  # Calls start_blocking once the event loop starts
    loop.run_forever()

相关文章