Last active
February 22, 2024 15:30
-
-
Save SurendraTamang/a6e5fe305af8448cec3808d745461b3b to your computer and use it in GitHub Desktop.
Asynchornous Programming in Python - asyncio.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 theasyncio.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 withasyncio.sleep(5)
: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.Asynchronous programming: Asynchronous programming in Python relies on coroutines, which can voluntarily yield control to the event loop using
await
. When a coroutine encounters anawait
statement, it temporarily suspends its execution, allowing other coroutines to run. In the case ofawait asyncio.sleep(5)
, the coroutine is paused until the sleep operation completes, but the event loop continues processing other tasks in the meantime.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.