Converting concurrent futures to Asyncio python3.7

人走茶凉 提交于 2019-12-11 06:15:30

问题


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)

回答1:


Here you go:

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

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



来源:https://stackoverflow.com/questions/57211473/converting-concurrent-futures-to-asyncio-python3-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!