Code Explanation:
1. Importing the asyncio Library
import asyncio
This imports the asyncio module — a built-in Python library used for writing asynchronous (non-blocking) code.
It allows multiple operations (like waiting, I/O, etc.) to run concurrently instead of one-by-one.
2. Defining an Asynchronous Function
async def double(x):
The async def keyword defines a coroutine function — a special kind of function that supports asynchronous operations.
Here, double(x) will take an argument x and run asynchronously when awaited.
3. Simulating a Delay
await asyncio.sleep(0.05)
The await keyword pauses execution of this coroutine for 0.05 seconds without blocking other tasks.
During this pause, other async functions (like another double()) can run — that’s what makes it concurrent.
4. Returning the Computation Result
return x * 2
After the 0.05-second delay, it returns twice the input value (x * 2).
For example, if x = 3, it returns 6.
5. Defining the Main Coroutine
async def main():
Another coroutine named main() — it will control the execution of the program.
This function will call multiple async tasks and gather their results.
6. Running Multiple Async Functions Concurrently
res = await asyncio.gather(double(2), double(3))
asyncio.gather() runs multiple coroutines at the same time (here, double(2) and double(3)).
Both start together, each waits 0.05s, and then return results [4, 6].
The await ensures we wait until all of them are finished and then store their results in res.
7. Printing the Combined Result
print(sum(res))
res is [4, 6].
sum(res) = 4 + 6 = 10.
So, the program prints:
10
8. Running the Event Loop
asyncio.run(main())
This starts the event loop, which executes the asynchronous tasks defined in main().
Once finished, the loop closes automatically.
Final Output:
10


0 Comments:
Post a Comment