Code Explanation:
1. Import the asyncio module
import asyncio
Imports Python’s built-in asynchronous I/O library.
It lets us run async functions concurrently (without threads).
2. Define an async function
async def f(x):
return x + 2
async def defines a coroutine (special function).
Takes input x and returns x + 2.
Example: f(1) returns 3, f(2) returns 4.
3. Define the main coroutine
async def main():
res = await asyncio.gather(f(1), f(2), f(3))
print(sum(res))
async def main() is the entry coroutine.
Inside it:
asyncio.gather(f(1), f(2), f(3)) runs all three coroutines concurrently.
It collects results into a list: [3, 4, 5].
await pauses main() until all tasks finish.
sum(res) = 3 + 4 + 5 = 12.
4. Run the event loop
asyncio.run(main())
Starts the event loop and executes main().
Runs until all async tasks inside main() are complete.
Final Output
12


0 Comments:
Post a Comment