Coroutine in Python with Examples

In this tutorial, we are going to learn about coroutine in Python. We will discuss the coroutines  what is the purpose of using coroutine, advantages , execution of coroutines and example

What are Coroutines?

In Python, a coroutine is a special type of function that can pause execution and later resume from where it left off. Coroutines enable the concurrent execution of multiple tasks or applications, promoting efficient utilization of resources and responsiveness in handling various operations simultaneously.

Purpose of Coroutine

They allow multiple I/O operations tasks to run concurrently without being blocked by one another, improving overall performance and responsiveness.  Coroutines are designed to handle concurrent tasks efficiently, especially in where tasks involve waiting for I/O operations like reading from a file, making network requests, or waiting for user input.

Subroutines

Knowing about subroutines, or functions in Python, can provide a helpful foundation for understanding coroutines.

  • Subroutines and coroutines are both ways of organizing code to make it more modular, reusable, and easier to understand.
  • subroutines encapsulate a block of code that can be called from other parts of the program, while coroutines extend this concept by allowing functions to pause and resume their execution, typically to handle asynchronous tasks.

Flowchart

Creating a flowchart that illustrates the relationship between coroutines and subroutines in Python

+-------------------------------------------+
|                   Program                 |
+---------------------+---------------------+
                      |
                      v
               +-------------+
               | Subroutine 1|
               +-------------+
                      |
                      v
               +-------------+
               | Subroutine 2|
               +-------------+
                      |
                      v
               +-------------+
               |   Coroutine |
               +-------------+
                      |
                      v
               +-------------+
               |   Coroutine |
               +-------------+
                      |
                      v
               +-------------+
               |   Coroutine |
               +-------------+

 

  • The “Program” box represents the main execution of the Python program
  • “Subroutine 1” and “Subroutine 2” represent regular functions (subroutines) that are called from the main program or from other functions.
  • The “Coroutine” boxes shows, which are functions marked with the async keyword and can be paused and resumed using await. Coroutines can be called from the main program or from other coroutines.

Example

import asyncio

async def greet(name):
    print("Hello,", name)
    await asyncio.sleep(1)  # Simulate asynchronous operation
    print("Goodbye,", name)

async def main():
    await greet("Alice")
    await greet("Bob")

asyncio.run(main())
Output:
Hello, Alice
(Gap of approximately 1 second)
Goodbye, Alice
Hello, Bob
(Gap of approximately 1 second)
Goodbye, Bob

Advantages Of Coroutines

  • Coroutines provide a structured way to write asynchronous code in Python. They allow tasks to be executed concurrently without blocking the event loop
  • Unlike traditional threading or multiprocessing approaches, coroutines are lightweight and have low overhead
  • This helps in better overall performance and scalability in applications that handle multiple concurrent tasks.
  • They follow a sequential programming model, making it easier to understand flow of the program

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top