You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:继承threading.Thread的类运行async任务报错的解决方法

解决RuntimeWarning: coroutine 'Mixer.run' was never awaited问题

问题根源在于threading.Thread的run()方法是同步执行逻辑的,你把它定义成async函数后,线程调用它时只会得到一个未执行的协程对象,不会自动触发异步执行,所以抛出这个警告。

下面是两种可行的解决方式:

方式一:拆分同步与异步逻辑(推荐)

把异步逻辑放到单独的协程方法里,在同步的run()中启动asyncio事件循环来执行这个协程:

import threading
import asyncio
from app.food import recipes

class Mixer(threading.Thread):
    def __init__(self):
        super().__init__()  # 用super继承比直接调用父类__init__更规范
    
    def run(self):
        # 在子线程内启动asyncio事件循环,运行异步逻辑
        asyncio.run(self._async_run())
    
    async def _async_run(self):
        while True:
            ingredients = await recipes.get()

方式二:添加优雅停止机制(进阶)

如果你的异步循环是无限运行的,建议加上停止标志,方便后续优雅终止线程:

import threading
import asyncio
from app.food import recipes

class Mixer(threading.Thread):
    def __init__(self):
        super().__init__()
        self._stop_flag = threading.Event()  # 线程安全的停止标志
    
    def stop(self):
        self._stop_flag.set()  # 设置停止标志
    
    def run(self):
        asyncio.run(self._async_run())
    
    async def _async_run(self):
        # 循环直到收到停止信号
        while not self._stop_flag.is_set():
            ingredients = await recipes.get()

使用时只需调用mixer.stop()即可终止异步循环。

内容的提问来源于stack exchange,提问作者sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:40:40