You need to enable JavaScript to run this app. 在独立线程运行asyncio事件循环遇报错:需传入协程对象
优惠活动
大模型
产品
解决方案
定价
更多

在独立线程运行asyncio事件循环遇报错:需传入协程对象

问题

我开发的应用组件需要在独立线程中运行IOLoop,实现周期性调度大量异步任务。我尝试在后台线程中创建新的IOLOOP并启动循环,操作步骤如下:

  • 在后台线程中创建事件循环;
  • 启动线程并调用asyncio.run_coroutine_threadsafe(self._start, self._loop)。

附上实现代码:

import asyncio
from contextlib import suppress

from threading import Thread


class AsyncScheduler(object):
    """
    Async Schedule Class.

    This class:
        - Will run on  a separate event loop on a separate thread.
        - Will periodically(every minute) schedule tasks for Requester.
    """

    def __init__(self, batch_manager, requester):
       
        self._requester = requester
        self._is_started = False
        self._tasks = []
        self._loop = None
        self.start()

    def start(self):
        """
        Start a new event loop in a thread.
        call eventloop.run(self._start)
        :return:
        """
        print("STARTING")
        self._loop = asyncio.new_event_loop()
        # start new loop in thread.
        Thread(target=self._loop.run_forever).start()
        asyncio.run_coroutine_threadsafe(self._start, self._loop)

    def stop(self):
        if self._loop:
            # cancel tasks
            self._loop.call_soon_threadsafe(self._stop)
            # stop the loop.
            self._loop.stop()

    

    async def _start(self):
        """
        Create three tasks for 3 API versions.
        Schedule Each tasks on the event loop using
        asyncio.gather.
        :return:
        """
        versions = [1, 2, 3]
        print("ASYNC START")

        if not self._is_started:
            self._is_started = True
            for version in versions:
                self._tasks.append(
                    self.create_task(60, version)
                )
            await asyncio.gather(*self._tasks)


    async def _stop(self):
        for task in self._tasks:
            task.cancel()
            with suppress(asyncio.CancelledError):
                await task

    async def execute(self, api_version):
        """
        This method gets the batch to be executed and
        tells the requester to run it.
        :param api_version:
        :return:
        """
        
        await self._requester.run()

    async def create_task(self, sleep_time, api_version):
        """
        Calls the tasks in infinite loop.
        :param sleep_time:
        :param api_version:
        :return:
        """
        while True:
            print("EVER CALLED")
            await self.execute(api_version)
            await asyncio.sleep(sleep_time)

代码执行逻辑:

  1. 在__init__中调用start方法;
  2. 在start方法里,在新线程内创建eventloop并尝试通过可等待对象启动循环。

实际运行时self._start根本没被调用,还弹出错误[A coroutine object is required],请问哪里操作错了?

解决方案

核心错误点

  1. run_coroutine_threadsafe参数传错:这个方法要求传入协程对象,但你传的是协程函数self._start,必须改成调用函数生成协程对象self._start()。
  2. _stop方法调用方式错误:call_soon_threadsafe无法直接执行协程,得用asyncio.run_coroutine_threadsafe来调度协程。
  3. 任务存储未正确处理:create_task是协程函数,直接存到self._tasks里的是协程对象,不是可跟踪的任务对象,需要用asyncio.create_task包装后再存储。

修正后的完整代码

import asyncio
from contextlib import suppress
from threading import Thread


class AsyncScheduler(object):
    """
    Async Schedule Class.

    This class:
        - Runs on a separate event loop in a separate thread.
        - Periodically (every minute) schedules tasks for Requester.
    """

    def __init__(self, batch_manager, requester):
        self._requester = requester
        self._is_started = False
        self._tasks = []
        self._loop = None
        self.start()

    def start(self):
        """Start a new event loop in a thread and schedule the _start coroutine."""
        print("STARTING")
        self._loop = asyncio.new_event_loop()
        # 把线程设为守护线程,避免程序退出时线程残留
        Thread(target=self._loop.run_forever, daemon=True).start()
        # 传入协程对象而非函数
        asyncio.run_coroutine_threadsafe(self._start(), self._loop)

    def stop(self):
        if self._loop:
            # 安全调度_stop协程到目标线程的事件循环
            asyncio.run_coroutine_threadsafe(self._stop(), self._loop)
            # 任务取消后再停止事件循环
            self._loop.call_soon_threadsafe(self._loop.stop)

    async def _start(self):
        """Create and schedule tasks for each API version."""
        versions = [1, 2, 3]
        print("ASYNC START")

        if not self._is_started:
            self._is_started = True
            for version in versions:
                # 用asyncio.create_task包装协程,生成可跟踪的任务对象
                task = asyncio.create_task(self.create_task(60, version))
                self._tasks.append(task)
            await asyncio.gather(*self._tasks)

    async def _stop(self):
        """Cancel all running tasks and wait for them to finish."""
        for task in self._tasks:
            if not task.done():
                task.cancel()
                with suppress(asyncio.CancelledError):
                    await task
        self._tasks.clear()

    async def execute(self, api_version):
        """Trigger the requester to run the batch for the given API version."""
        await self._requester.run()

    async def create_task(self, sleep_time, api_version):
        """Infinite loop that executes the task periodically."""
        while True:
            print("EVER CALLED")
            await self.execute(api_version)
            await asyncio.sleep(sleep_time)

关键修复说明

  • 启动协程:把asyncio.run_coroutine_threadsafe(self._start, self._loop)改成asyncio.run_coroutine_threadsafe(self._start(), self._loop),确保传入的是已经实例化的协程对象。
  • 停止协程:用asyncio.run_coroutine_threadsafe(self._stop(), self._loop)替代原有的call_soon_threadsafe,因为后者只能处理普通函数,无法处理协程。
  • 任务管理:使用asyncio.create_task将周期性任务的协程包装成任务对象,这样才能正确跟踪任务状态、执行取消操作。
  • 守护线程:启动线程时添加daemon=True,保证主程序退出时,后台线程会自动终止,不会滞留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:40:30