2

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)
Aladine
  • 185
  • 3
  • 16

1 Answers1

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.

Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159