Python中async函数为何无法并行运行?如何解决?
原因分析
asyncio的协程基于单线程事件循环调度,只有当当前协程通过await主动让出CPU控制权时,事件循环才会切换到其他任务执行。你的print_foo是无限循环,里面只有print("foo")操作,没有任何await语句——这会让它一直霸占事件循环,完全不给print_bar运行的机会,所以只能看到一连串的foo。
解决方法
要让两个协程交替执行,需要在每个循环中加入能让协程让出CPU的操作,最常用的是await asyncio.sleep(0)(立即让出控制权,触发事件循环调度其他任务),也可以根据需求设置实际休眠时长(比如await asyncio.sleep(0.1),让输出更规整)。
修改后的代码示例:
import asyncio async def print_foo(): while True: print("foo") await asyncio.sleep(0) # 让出CPU,给其他协程运行机会 async def print_bar(): while True: print("bar") await asyncio.sleep(0) async def main(): async with asyncio.TaskGroup() as tg: task1 = tg.create_task(print_foo()) task2 = tg.create_task(print_bar()) if __name__ == "__main__": asyncio.run(main())
如果需要严格交替的foo和bar输出,可以给两个任务设置相同的休眠时长(比如0.1秒),这样任务切换会更规律,输出更接近预期效果。
内容的提问来源于stack exchange,提问作者Eind997
相关产品推荐
相关产品推荐

