Asynchronous Operations (Coroutine) in Python

Asynchronous Operations (Coroutine) in Python

·

2 min read

Asynchronous operations are operations that run independently of the main program flow and don't block the execution of the program. In other words, asynchronous operations allow the program to continue executing other tasks while it waits for the operation to complete.

In Python, asynchronous operations can be performed using coroutines, which are functions marked with the "async" keyword. Coroutines allow you to write asynchronous code that is more readable and maintainable than using threads or callbacks.

Here's an example to help illustrate how asynchronous operations work:

import asyncio

async def fetch_data():
    # Perform an asynchronous operation (e.g. fetch data from a network or database)
    await asyncio.sleep(2)  # Wait for 2 seconds
    return "Data fetched"

async def main():
    # Start the asynchronous operation
    result = await fetch_data()
    print(result)

asyncio.run(main())

What is coroutine?

A coroutine is a special type of function in Python that is used to handle asynchronous operations. Unlike normal functions, coroutines can be suspended and resumed multiple times, allowing other parts of the code to run while they are waiting for an operation to complete.

Coroutines are defined using the "async" keyword before the function definition. They can contain one or more "await" expressions, which pause the execution of the coroutine until the result of an asynchronous operation is returned.

Coroutines are similar to threads, but they are more lightweight and efficient, as they only consume resources when they are actually running. Additionally, coroutines can be used to handle large numbers of parallel operations without the overhead of creating a separate thread for each one.

import asyncio

async def my_coroutine(x,whichone):
    print("Running coroutine...",whichone)
    await asyncio.sleep(x)
    print("Coroutine complete.",whichone)

async def main():
    await asyncio.gather(my_coroutine(1,1), my_coroutine(2,2), my_coroutine(3,3))
    print('all complete.')

asyncio.run(main())

In this example, the "my_coroutine" function is a coroutine that runs for a specified amount of time and then prints a message indicating that it is complete. The "main" function uses the "asyncio.gather" function to run multiple coroutines in parallel, and the "asyncio.run" function is used to run the "main" function and wait for it to complete.