2024-10-08 12:15:04 +00:00
|
|
|
#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)
|
2024-10-10 03:31:09 +00:00
|
|
|
self._worker_task = None
|
|
|
|
self._loop_running = threading.Event()
|
2024-10-08 12:15:04 +00:00
|
|
|
self._thread.start()
|
|
|
|
|
|
|
|
def _run_loop(self):
|
2024-10-10 11:01:13 +00:00
|
|
|
print('_run_loop')
|
2024-10-10 03:31:09 +00:00
|
|
|
self._loop_running.set()
|
2024-10-10 11:01:13 +00:00
|
|
|
asyncio.set_event_loop(self._loop)
|
2024-10-10 03:31:09 +00:00
|
|
|
self._loop.run_forever()
|
2024-10-08 12:15:04 +00:00
|
|
|
|
|
|
|
async def _worker(self):
|
2024-10-10 11:01:13 +00:00
|
|
|
print('_worker')
|
2024-10-10 03:31:09 +00:00
|
|
|
while self._loop_running.is_set():
|
2024-10-08 12:15:04 +00:00
|
|
|
task = await self._queue.get()
|
|
|
|
if task is None:
|
|
|
|
break
|
2024-10-10 11:01:13 +00:00
|
|
|
print('run task')
|
2024-10-08 12:15:04 +00:00
|
|
|
await task
|
|
|
|
self._queue.task_done()
|
2024-10-10 11:01:13 +00:00
|
|
|
print('_worker finish')
|
2024-10-08 12:15:04 +00:00
|
|
|
|
|
|
|
def add_task(self, coro):
|
2024-10-10 11:01:13 +00:00
|
|
|
print('add_task')
|
2024-10-08 12:15:04 +00:00
|
|
|
asyncio.run_coroutine_threadsafe(self._queue.put(coro), self._loop)
|
|
|
|
|
|
|
|
def start_worker(self):
|
2024-10-10 03:31:09 +00:00
|
|
|
if not self._worker_task:
|
|
|
|
self._worker_task = asyncio.run_coroutine_threadsafe(self._worker(), self._loop)
|
2024-10-08 12:15:04 +00:00
|
|
|
|
|
|
|
def stop(self):
|
2024-10-10 03:31:09 +00:00
|
|
|
self._loop_running.clear()
|
2024-10-08 12:15:04 +00:00
|
|
|
asyncio.run_coroutine_threadsafe(self._queue.put(None), self._loop).result()
|
2024-10-10 03:31:09 +00:00
|
|
|
if self._worker_task:
|
|
|
|
self._worker_task.result()
|
2024-10-08 12:15:04 +00:00
|
|
|
self._loop.call_soon_threadsafe(self._loop.stop)
|
2024-10-10 03:31:09 +00:00
|
|
|
self._thread.join()
|
|
|
|
self._loop.close()
|