使用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()) 创建一个线程的本地事件循环。
推荐阅读
- 机器学习|机器学习入门(开发环境搭建)
- python学习|学习记录6
- python|BAT大厂都在用的Docker。学会这三招,面试、工作轻松hold住
- Python|8个无需编写代码即可使用Python内置库的方法
- Python|Python打开修图的最新方式,直男必学
- Python|【python量化】将Transformer模型用于股票价格预测
- Python实战项目|Python+Selenium实现短视频自动上传与发布
- Python实战项目|如何用 Python 实现企业微信通知
- Python|【Python】和【Jupyter notebook】的正确安装方式