Python 3.12异步程序中await调用疑似阻塞问题求助
异步代码阻塞原因及解决办法
阻塞原因
你的代码出现阻塞的核心问题是任务采用了批次同步执行的模式:
main函数里的while True循环,每次都会调用await asyncio.gather(taskOne(), taskTwo(), taskThree()),这意味着必须等这三个任务全部执行完毕,才会进入下一次循环。- 当
taskThree执行到await self.taskFour(...)时,taskThree会暂停,但整个gather调用必须等待taskThree完成才能结束当前批次。而taskFour里的asyncio.sleep(10)会让taskThree暂停10秒,这期间当前批次的gather还没结束,下一批次的taskTwo根本没机会启动,所以你看不到taskTwo的输出。
简单来说:你是把三个任务当成一批批执行的,而非让它们持续并发运行。
解决办法
要实现真正的并发,需要让每个任务自身成为持续运行的独立协程,然后一次性启动所有协程,让事件循环自动调度它们:
修改后的核心代码
async def taskOne(self): while True: current_time = time.time() if current_time - self.start_time_one > self.task_delay_one: print("Do task one") self.start_time_one = current_time await asyncio.sleep(1) # 让出控制权,让其他协程运行 async def taskTwo(self): while True: current_time = time.time() if current_time - self.start_time_two > self.task_delay_two: print("Do task Two") self.start_time_two = current_time await asyncio.sleep(1) async def taskThree(self): while True: current_time = time.time() if current_time - self.start_time_three > self.task_delay_three: print(self.c[3] + "Do task three") self.start_time_three = current_time returnVal = await self.taskFour(self.task_four_var) print(f"Task 4 has been returned with variable: {returnVal}") self.task_four_var = returnVal await asyncio.sleep(1) async def main(self): try: # 一次性启动所有持续运行的协程,事件循环会调度它们并发执行 await asyncio.gather(self.taskOne(), self.taskTwo(), self.taskThree()) except KeyboardInterrupt: print("User Ended Program, Exiting")
修改说明
- 给每个任务(taskOne/taskTwo/taskThree)内部加上
while True循环,让它们自己持续运行,不再依赖main的循环。 - 每个任务循环末尾的
await asyncio.sleep(1)是关键:它会让当前协程暂停,给事件循环让出控制权,让其他协程有机会执行。 main函数只需要一次asyncio.gather调用,启动所有协程即可。事件循环会自动处理这些协程的调度,即使taskThree在等待taskFour的10秒,taskTwo和taskOne也能正常周期性执行。
内容的提问来源于stack exchange,提问作者ImogenWren
相关产品推荐
相关产品推荐

