将并发期货转换为 Asyncio python3.7 [英] Converting concurrent futures to Asyncio python3.7

查看:42
本文介绍了将并发期货转换为 Asyncio python3.7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am going to start looking at converting my code use asyncio. I cant find an example or explanation that I understand. I was wondering if someone could convert this simple code to use asyncio rather than concurrent futures? This was some old code that helped my understand how threading could help with speeding things up.

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)

推荐答案

给你:

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())

<小时>

您可能有兴趣阅读这篇文章以更好地了解 asyncio 的工作原理.


You may be interested in reading this article for better understanding of how asyncio works.

这篇关于将并发期货转换为 Asyncio python3.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆