asyncio|asyncio 多线程附加协程,在一个线程内运行一个事件循环

使用threading.Thread 和asyncio.new_event_loop 我们可以创建具有唯一事件循环实例的线程实例。

import asyncio import threadingdef 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) for _ in range(10)] start_threads(*workers) join_threads(*workers)if __name__ == '__main__': main()打印 Inside the print coro on 6154842112 ((22,), {'a': 33}) Inside the print coro on 6171668480 ((22,), {'a': 33}) Inside the print coro on 6154842112 ((22,), {'a': 33}) Inside the print coro on 6205321216 ((22,), {'a': 33}) Inside the print coro on 6188494848 ((22,), {'a': 33}) Inside the print coro on 6171668480 ((22,), {'a': 33}) Inside the print coro on 6154842112 ((22,), {'a': 33}) Inside the print coro on 6205321216 ((22,), {'a': 33}) Inside the print coro on 6188494848 ((22,), {'a': 33}) Inside the print coro on 6171668480 ((22,), {'a': 33})

DefaultLoopPolicy检查每个线程的循环,并且不允许通过asyncio.get_event_loop在主线程之外创建循环。
【asyncio|asyncio 多线程附加协程,在一个线程内运行一个事件循环】因此,我们必须通过asyncio.set_event_loop(asyncio.new_event_loop()) 创建一个线程的本地事件循环。

    推荐阅读