Asynchronous Programming in Python

Asynchronous Programming in Python

Imagine an ecosystem filled with animals of all shapes and sizes, each going about their tasks independently yet harmoniously. This is similar to asynchronous programming in Python, where tasks can execute concurrently, each contributing to the overall efficiency and responsiveness of the system.

In our digital ecosystem, asynchronous programming allows to perform tasks concurrently.

import asyncio
async def lion():
    print("The lion roars")
    await asyncio.sleep(1)
    print("The lion rests after roaring")

async def bird():
    print("The bird sings")
    await asyncio.sleep(0.5)
    print("The bird pauses its song")

async def main():
    await asyncio.gather(lion(), bird())

asyncio.run(main())

In above code we defined an asynchronous function lion() using the async keyword before the def keyword. When you mark a function with async, you're telling Python that the function is capable of pausing and resuming its execution, allowing other tasks to run in between.

Within the function, we print a message then we use await asyncio.sleep(1) to pause the execution of this coroutine for 1 second , and finally, we print a message print("The lion rests after roaring") .

The await keyword is used to pause the execution of the coroutine until an awaitable object (such as another coroutine or a Task) completes its execution.

In the context of the line await asyncio.sleep(1), here's what happens:

  1. asyncio.sleep(1) pauses the execution of the current coroutine for the specified duration (in this case, 1 sec) without blocking the event loop. It's commonly used to introduce delays or simulate asynchronous operations that take time to complete.

  2. When the await keyword is placed before asyncio.sleep(1), it tells the event loop to suspend the execution of the current coroutine until the sleep operation is complete.

  3. While the coroutine is awaiting the completion of asyncio.sleep(1), the event loop is free to execute other tasks or coroutines concurrently. This allows for more efficient use of resources and enables responsiveness in asynchronous programs, especially in scenarios where tasks are I/O-bound and spend a lot of time waiting for external operations to complete.

async def main():
    await asyncio.gather(lion(), bird())

the main() coroutine function, which serves as the entry point for our asynchronous program. Inside main(), we use asyncio.gather() to run multiple asynchronous tasks concurrently. We pass in the coroutines lion() and bird() to asyncio.gather() to execute them concurrently.

Conclusion:
In conclusion, Python's 'await' keyword changes asynchronous programming, allowing functions to pause until tasks complete, ensuring non-blocking execution and optimizing performance. Its seamless integration enables developers to create responsive applications capable of handling concurrent operations efficiently.