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

如何将asyncio与现有的阻止库一起使用?

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

如何将asyncio与现有的阻止库一起使用?

这里有两个问题:首先,如何异步运行阻塞代码,其次,如何并行运行异步代码(异步是单线程的,因此GIL仍然适用,因此不是 真正的 并发,但我离题了。

可以使用asyncio.ensure_future创建并行任务,如此处所述。

要运行同步代码,您将需要在executor中运行阻塞代码。例:

import concurrent.futuresimport asyncioimport timedef blocking(delay):    time.sleep(delay)    print('Completed.')async def non_blocking(loop, executor):    # Run three of the blocking tasks concurrently. asyncio.wait will    # automatically wrap these in Tasks. If you want explicit access    # to the tasks themselves, use asyncio.ensure_future, or add a    # "done, pending = asyncio.wait..." assignment    await asyncio.wait(        fs={ # Returns after delay=12 seconds loop.run_in_executor(executor, blocking, 12), # Returns after delay=14 seconds loop.run_in_executor(executor, blocking, 14), # Returns after delay=16 seconds loop.run_in_executor(executor, blocking, 16)        },        return_when=asyncio.ALL_COMPLETED    )loop = asyncio.get_event_loop()executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)loop.run_until_complete(non_blocking(loop, executor))

如果要使用for循环调度这些任务(如您的示例中所示),则有几种不同的策略,但是基本方法是使用for循环(或列表理解等) 调度
任务,并通过asyncio等待它们。等待, 然后 检索结果。例:

done, pending = await asyncio.wait(    fs=[loop.run_in_executor(executor, blocking_foo, *args) for args in inps],    return_when=asyncio.ALL_COMPLETED)# Note that any errors raise during the above will be raised here; to# handle errors you will need to call task.exception() and check if it# is not None before calling task.result()results = [task.result() for task in done]


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

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

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