Skip to content

Instantly share code, notes, and snippets.

@SurendraTamang
Last active February 22, 2024 15:30
Show Gist options
  • Save SurendraTamang/a6e5fe305af8448cec3808d745461b3b to your computer and use it in GitHub Desktop.
Save SurendraTamang/a6e5fe305af8448cec3808d745461b3b to your computer and use it in GitHub Desktop.
Asynchornous Programming in Python - asyncio.py
import asyncio
import time
# What is the difference between this I find same ?
# Coroutine
async def my_coroutine():
print("Coroutine is starting...")
await asyncio.sleep(5) # Simulate a non-blocking delay
print("Coroutine resumed after waiting")
def my_regular_function():
print("Regular function called")
time.sleep(1)
print("Regular function resumed after waiting")
asyncio.run(my_coroutine())
my_regular_function()
@SurendraTamang
Copy link
Author

In the provided code, both asyncio.sleep(5) within the coroutine my_coroutine() and time.sleep(1) within the regular function my_regular_function() introduce a delay. However, they operate differently:

  1. asyncio.sleep(5) within my_coroutine():

    • This is an asynchronous sleep function provided by the asyncio module.
    • When the coroutine encounters await asyncio.sleep(5), it suspends its execution and allows other coroutines or tasks to run in the meantime.
    • During this suspension, the event loop continues to process other asynchronous tasks.
    • After the specified time (5 seconds), the coroutine is automatically resumed, and execution continues from where it left off.
    • While waiting, the event loop is free to run other tasks, ensuring efficient utilization of resources.
  2. time.sleep(1) within my_regular_function():

    • This is a synchronous sleep function provided by the time module.
    • When the regular function my_regular_function() calls time.sleep(1), it blocks the entire thread's execution for the specified time (1 second) without allowing other tasks to proceed.
    • During this time, the program is essentially idle, waiting for the sleep to complete.
    • After the specified time, execution of the regular function resumes.
    • However, during this sleep, no other tasks or coroutines can run, potentially leading to reduced concurrency and performance degradation, especially in asynchronous contexts.

In summary, both functions introduce a delay, but asyncio.sleep(5) within a coroutine allows other tasks to run concurrently while waiting, making it suitable for asynchronous programming and non-blocking I/O operations. On the other hand, time.sleep(1) within a regular function blocks the entire thread, potentially affecting concurrency and responsiveness, and is more suitable for synchronous operations where blocking is acceptable.

@SurendraTamang
Copy link
Author

Coroutine long running task is suspends its execution and allows other coroutines or tasks to run in the meantime.

@SurendraTamang
Copy link
Author

In Python's asynchronous programming model, the await keyword is used to pause the execution of a coroutine until a particular asynchronous operation completes.

When you call await asyncio.sleep(5), you are essentially telling the coroutine to pause its execution for 5 seconds or until the asyncio.sleep(5) operation completes, whichever happens first. During this waiting period, the event loop is free to execute other coroutines or tasks, ensuring that your program remains responsive and can handle multiple concurrent operations efficiently.

Here's why await is used with asyncio.sleep(5):

  1. Non-blocking behavior: Unlike synchronous sleep functions (e.g., time.sleep(5)), which would block the entire thread, asyncio.sleep(5) is non-blocking. This means that while the coroutine awaits the completion of the sleep operation, other coroutines or tasks can continue to run concurrently, improving overall program efficiency.

  2. Asynchronous programming: Asynchronous programming in Python relies on coroutines, which can voluntarily yield control to the event loop using await. When a coroutine encounters an await statement, it temporarily suspends its execution, allowing other coroutines to run. In the case of await asyncio.sleep(5), the coroutine is paused until the sleep operation completes, but the event loop continues processing other tasks in the meantime.

  3. Integration with asyncio event loop: await asyncio.sleep(5) integrates seamlessly with the asyncio event loop. It schedules the sleep operation in the event loop and returns control to the event loop until the specified time has elapsed. Once the sleep is complete, the event loop resumes the execution of the coroutine.

In summary, await asyncio.sleep(5) is used to introduce a non-blocking delay within a coroutine, allowing other asynchronous tasks to proceed while waiting for the specified time to elapse. It's a key mechanism in Python's asynchronous programming model for achieving concurrency and responsiveness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment