#encoding = utf8 import asyncio import threading class AsyncTaskQueue: def __init__(self): self._queue = asyncio.Queue() self._loop = asyncio.new_event_loop() self._thread = threading.Thread(target=self._run_loop) self.worker_task = None self.loop_running = threading.Event() self._thread.start() def _run_loop(self): asyncio.set_event_loop(self._loop) self.loop_running.set() # 设置事件,表明事件循环正在运行 self._loop.run_forever() # 启动事件循环 async def _worker(self): while True: task = await self._queue.get() if task is None: break await task self._queue.task_done() def add_task(self, coro): asyncio.run_coroutine_threadsafe(self._queue.put(coro), self._loop) def start_worker(self): if not self.worker_task: self.worker_task = asyncio.run_coroutine_threadsafe(self._worker(), self._loop) def stop(self): asyncio.run_coroutine_threadsafe(self._queue.put(None), self._loop).result() if self.worker_task: self.worker_task.result() self._loop.call_soon_threadsafe(self._loop.stop) self._thread.join() # 等待线程结束 self._loop.close() # 关闭事件循环