2024-10-08 12:15:04 +00:00
|
|
|
#encoding = utf8
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
import threading
|
|
|
|
|
|
|
|
|
|
|
|
class AsyncTaskQueue:
|
2024-10-14 10:20:55 +00:00
|
|
|
def __init__(self, work_num=1):
|
2024-10-08 12:15:04 +00:00
|
|
|
self._queue = asyncio.Queue()
|
2024-10-14 10:20:55 +00:00
|
|
|
self._worker_num = work_num
|
|
|
|
self._current_worker_num = work_num
|
2024-10-08 12:15:04 +00:00
|
|
|
self._thread = threading.Thread(target=self._run_loop)
|
|
|
|
self._thread.start()
|
2024-10-14 10:20:55 +00:00
|
|
|
self.__loop = None
|
2024-10-08 12:15:04 +00:00
|
|
|
|
|
|
|
def _run_loop(self):
|
2024-10-10 11:01:13 +00:00
|
|
|
print('_run_loop')
|
2024-10-14 10:20:55 +00:00
|
|
|
self.__loop = asyncio.new_event_loop()
|
|
|
|
asyncio.set_event_loop(self.__loop)
|
|
|
|
self._tasks = [self.__loop.create_task(self._worker()) for _ in range(self._worker_num)]
|
|
|
|
self.__loop.run_forever()
|
|
|
|
print("exit run")
|
|
|
|
if not self.__loop.is_closed():
|
|
|
|
self.__loop.close()
|
2024-10-08 12:15:04 +00:00
|
|
|
|
|
|
|
async def _worker(self):
|
2024-10-10 11:01:13 +00:00
|
|
|
print('_worker')
|
2024-10-13 14:49:17 +00:00
|
|
|
while True:
|
2024-11-05 11:40:03 +00:00
|
|
|
task = await self._queue.get()
|
2024-11-06 12:31:23 +00:00
|
|
|
print(f"Get task size: {self._queue.qsize()}")
|
2024-11-05 11:40:03 +00:00
|
|
|
if task is None: # None as a stop signal
|
|
|
|
break
|
2024-10-14 10:20:55 +00:00
|
|
|
|
2024-11-05 11:40:03 +00:00
|
|
|
func, *args = task # Unpack task
|
|
|
|
print(f"Executing task with args: {args}")
|
|
|
|
await func(*args) # Execute async function
|
|
|
|
self._queue.task_done()
|
2024-10-14 10:20:55 +00:00
|
|
|
|
2024-10-10 11:01:13 +00:00
|
|
|
print('_worker finish')
|
2024-11-05 11:40:03 +00:00
|
|
|
self._current_worker_num -= 1
|
2024-10-14 10:20:55 +00:00
|
|
|
if self._current_worker_num == 0:
|
|
|
|
print('loop stop')
|
|
|
|
self.__loop.stop()
|
2024-10-08 12:15:04 +00:00
|
|
|
|
2024-10-14 10:20:55 +00:00
|
|
|
def add_task(self, func, *args):
|
2024-11-06 12:31:23 +00:00
|
|
|
return self.__loop.call_soon_threadsafe(self._queue.put_nowait, (func, *args))
|
2024-10-08 12:15:04 +00:00
|
|
|
|
2024-10-14 10:20:55 +00:00
|
|
|
def stop_workers(self):
|
|
|
|
for _ in range(self._worker_num):
|
2024-11-05 11:40:03 +00:00
|
|
|
self.add_task(None) # Send stop signal
|
2024-10-08 12:15:04 +00:00
|
|
|
|
2024-10-19 10:47:34 +00:00
|
|
|
def clear(self):
|
|
|
|
while not self._queue.empty():
|
2024-11-05 11:40:03 +00:00
|
|
|
self._queue.get_nowait()
|
2024-10-19 10:47:34 +00:00
|
|
|
self._queue.task_done()
|
|
|
|
|
2024-10-08 12:15:04 +00:00
|
|
|
def stop(self):
|
2024-10-14 10:20:55 +00:00
|
|
|
self.stop_workers()
|
2024-10-10 03:31:09 +00:00
|
|
|
self._thread.join()
|