【问题标题】:Converting concurrent futures to Asyncio python3.7将并发期货转换为 Asyncio python3.7
【发布时间】:2019-07-25 23:53:39
【问题描述】:

我将开始研究使用 asyncio 转换我的代码。我找不到我理解的示例或解释。我想知道是否有人可以将这个简单的代码转换为使用 asyncio 而不是并发期货?这是一些旧代码,帮助我了解线程如何帮助加快速度。

import time
from concurrent import futures


def run(data):
        time.sleep(.5)
        print("Hello World")
        return


data = range(20)
max_workers = 10
concurrent = futures.ThreadPoolExecutor(max_workers)

with concurrent as ex:
    ex.map(run, data)

【问题讨论】:

    标签: python-asyncio python-3.7


    【解决方案1】:

    给你:

    import asyncio
    
    
    async def run(data):
        await asyncio.sleep(0.5)
        print("Hello World")
    
    
    async def main():
        await asyncio.gather(*[
            run(i) 
            for i 
            in range(20)
        ])
    
    
    asyncio.run(main())
    

    您可能有兴趣阅读 this article 以更好地了解 asyncio 的工作原理。

    【讨论】:

    • 非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多