theelk801
theelk801

Reputation: 33

Using Python async to compute things out of order

I'm trying to understand async and it's getting confusing. Here's basically what I'm trying to do asynchronously:

def process_data(i):
    time.sleep(5) # something involving i/o that takes some time
    return random.randint(0,10)

def main():
    return [process_data(i) for i in range(100)]

I don't actually care about the order of the output in this case but I should probably know how to do ordered and unordered anyway.

I'd appreciate any help, thanks!

Upvotes: 0

Views: 502

Answers (1)

Anh Do Hoang
Anh Do Hoang

Reputation: 156

For ordered result, you could use gather method

import asyncio
import random

async def process_data(i):
    await asyncio.sleep(1)
    return random.randint(0,10)

async def main():
    tasks = [process_data(i) for i in range(100)]
    result = await asyncio.gather(*tasks)
    print(result)

asyncio.run(main())

For unordered result, it is depending on the situations

Upvotes: 2

Related Questions