Python Asyncio两任务仅一个运行问题求助
问题分析与解决方案
嘿,这个坑我之前也踩过!核心问题出在你的同步函数完全阻塞了事件循环,导致另一个协程根本没机会运行。
为什么会出现这个情况?
你的job1_sync()和job2_sync()是纯同步的无限循环,没有任何能让事件循环"喘口气"的暂停点。当await self.job1_sync()执行时,这个同步函数会一直霸占着CPU,永远不会返回,事件循环被死死卡住,自然没法切换到job2()任务去执行。
要知道,asyncio的协程切换是协作式的——只有当当前协程主动让出CPU(比如执行await一个真正的异步操作),事件循环才会去调度其他任务。而你的同步函数完全不配合,一直跑到底,另一个任务只能闲置。
两种解决办法
办法1:把同步循环改成异步循环
在每次循环里加入await asyncio.sleep(0)(或者实际业务中的异步IO操作),主动给事件循环切换任务的机会:
import asyncio class Worker: async def job1(self): count = 0 while True: print('JOB A:', count) count += 1 await asyncio.sleep(0) # 让出CPU,让其他协程有机会运行 async def job2(self): count = 0 while True: print('JOB B:', count) count += 1 await asyncio.sleep(0) worker = Worker() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(asyncio.gather(worker.job1(), worker.job2()))
办法2:用线程池运行同步函数(适合无法修改同步代码的场景)
如果你的job1_sync和job2_sync是不能修改的同步耗时函数,可以把它们放到线程池里执行,避免阻塞事件循环:
import asyncio from concurrent.futures import ThreadPoolExecutor class Worker: def job1_sync(self): count = 0 while True: print('JOB A:', count) count += 1 def job2_sync(self): count = 0 while True: print('JOB B:', count) count += 1 async def job1(self): loop = asyncio.get_running_loop() # 把同步函数放到线程池执行 await loop.run_in_executor(ThreadPoolExecutor(), self.job1_sync) async def job2(self): loop = asyncio.get_running_loop() await loop.run_in_executor(ThreadPoolExecutor(), self.job2_sync) worker = Worker() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(asyncio.gather(worker.job1(), worker.job2()))
这样修改后,两个任务就能交替运行啦~
内容的提问来源于stack exchange,提问作者Wild Goat
相关产品推荐
相关产品推荐

