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

如何使用python的asyncio模块正确创建和运行并发任务?

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

如何使用python的asyncio模块正确创建和运行并发任务?

是的,事件循环中运行的任何协程将阻止其他协程和任务运行,除非它

  1. 使用
    yield from
    await
    (如果使用Python 3.5+)调用另一个协程。
  2. 退货。

这是因为

asyncio
是单线程的。事件循环运行的唯一方法是没有其他协程正在积极执行。使用
yieldfrom
/
await
暂时暂停协程,使事件循环有工作的机会。

您的示例代码很好,但是在很多情况下,您可能不希望开始时没有在事件循环内运行不执行异步I /
O的长时间运行的代码。在这些情况下,通常更适合

asyncio.loop.run_in_executor
在后台线程或进程中运行代码。
ProcessPoolExecutor
如果您的任务是CPU限制的,则是更好的选择;如果您
ThreadPoolExecutor
需要执行一些
asyncio
不友好的I
/ O ,则将使用它。

例如,您的两个循环完全受CPU限制,并且不共享任何状态,因此,最好的性能来自

ProcessPoolExecutor
于跨CPU并行运行每个循环:

import asynciofrom concurrent.futures import ProcessPoolExecutorprint('running async test')def say_boo():    i = 0    while True:        print('...boo {0}'.format(i))        i += 1def say_baa():    i = 0    while True:        print('...baa {0}'.format(i))        i += 1if __name__ == "__main__":    executor = ProcessPoolExecutor(2)    loop = asyncio.get_event_loop()    boo = asyncio.create_task(loop.run_in_executor(executor, say_boo))    baa = asyncio.create_task(loop.run_in_executor(executor, say_baa))    loop.run_forever()


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

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

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