使用threading.Thread 和asyncio.new_event_loop 我们可以创建具有唯一事件循环实例的线程实例。
import asyncio
import threading
def creat_event_loop_thread(worker, *args, **kwargs):
""""""
def _worker(*args, **kwargs):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(worker(*args, **kwargs))
finally:
loop.close()
return threading.Thread(target=_worker, args=args, kwargs=kwargs)
async def print_coro(*args, **kwargs):
print(f'Inside the print coro on {threading.get_ident()}', (args, kwargs))
def start_threads(*threads):
[thread.start() for thread in threads if isinstance(thread, threading.Thread)]
def join_threads(*threads):
[thread.join() for thread in threads if isinstance(thread, threading.Thread)]
def main():
workers = [creat_event_loop_thread(print_coro, 22, a=33)