run multiple tasks

Solutions on MaxInterview for run multiple tasks by the best coders in the world

showing results for - "run multiple tasks"
Melina
01 Aug 2020
1import asyncio
2
3async def factorial(name, number):
4    f = 1
5    for i in range(2, number + 1):
6        print(f"Task {name}: Compute factorial({number}), currently i={i}...")
7        await asyncio.sleep(1)
8        f *= i
9    print(f"Task {name}: factorial({number}) = {f}")
10    return f
11
12async def main():
13    # Schedule three calls *concurrently*:
14    L = await asyncio.gather(
15        factorial("A", 2),
16        factorial("B", 3),
17        factorial("C", 4),
18    )
19    print(L)
20
21asyncio.run(main())
22
23# Expected output:
24#
25#     Task A: Compute factorial(2), currently i=2...
26#     Task B: Compute factorial(3), currently i=2...
27#     Task C: Compute factorial(4), currently i=2...
28#     Task A: factorial(2) = 2
29#     Task B: Compute factorial(3), currently i=3...
30#     Task C: Compute factorial(4), currently i=3...
31#     Task B: factorial(3) = 6
32#     Task C: Compute factorial(4), currently i=4...
33#     Task C: factorial(4) = 24
34#     [2, 6, 24]
35
similar questions
queries leading to this page
run multiple tasks