Junior — Middle
What is asynchronous task execution using the asyncio module and how does it work?
sobes.tech AI
Answer from AI
The asyncio module in Python allows for asynchronous task execution, meaning it does not block the main thread of execution. This is achieved through an event loop that manages the execution of coroutines — special functions that can suspend their execution and yield control back to the loop.
Asynchronous execution is useful for input/output operations (such as network requests, file handling), where you can avoid waiting for the operation to complete and switch to other tasks.
Example of using asyncio:
import asyncio
async def say_hello():
print('Hello')
await asyncio.sleep(1) # simulate an asynchronous operation
print('World')
async def main():
await asyncio.gather(say_hello(), say_hello())
asyncio.run(main())
Here, two coroutines run in parallel, without blocking each other during the wait.