asyncio 将循环附加在线程上

asyncio 将循环附加在线程上,第1张

import asyncio
import threading


def create_event_loop_thread(workers,*args,**kwargs):
    def _worker(*args,**kwargs):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            loop.run_until_complete(workers(*args,**kwargs))
        finally:
            loop.close()
    return threading.Thread(target=_worker,args=args,kwargs=kwargs)

async def print_coro(*args,**kwargs):
    print(f"巴拉巴拉{threading.get_ident()}:{args}:{kwargs}")

def start_thread(th):
    [t.start() for t in th if isinstance(t,threading.Thread)]

def join_thread(th):
    [t.join() for t in th if isinstance(t,threading.Thread)]

def main():
    workers=[create_event_loop_thread(print_coro) for i in range(10)]
    start_thread(workers)
    join_thread(workers)

if __name__ == '__main__':
    main()

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/884128.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存