栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将python asyncio与线程结合在一起?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将python asyncio与线程结合在一起?

使用以下方法将方法委派给线程或子流程非常简单

baseEventLoop.run_in_executor

import asyncioimport timefrom concurrent.futures import ProcessPoolExecutordef cpu_bound_operation(x):    time.sleep(x) # This is some operation that is CPU-bound@asyncio.coroutinedef main():    # Run cpu_bound_operation in the ProcessPoolExecutor    # This will make your coroutine block, but won't block    # the event loop; other coroutines can run in meantime.    yield from loop.run_in_executor(p, cpu_bound_operation, 5)loop = asyncio.get_event_loop()p = ProcessPoolExecutor(2) # Create a ProcessPool with 2 processesloop.run_until_complete(main())

至于使用a

ProcessPoolExecutor
还是
ThreadPoolExecutor
,这很难说。腌制一个大物体肯定会消耗一些CPU周期,最初您会认为这
ProcessPoolExecutor
是可行的方法。但是,将100MB对象传递到
Process
池中的a将需要在主进程中腌制该实例,通过IPC将字节发送到子进程,在子进程中将其取消腌制,然后
再次
进行腌制,以便可以将其写入磁盘。鉴于此,我的猜测是,酸洗/去酸洗的开销将足够大
ThreadPoolExecutor
,即使使用GIL会对性能造成负面影响,您也最好使用。

也就是说,两种方法的测试都非常简单,并且可以确定找出来,所以您也可以这样做。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637816.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号