Created
July 21, 2024 16:20
-
-
Save j-thepac/f2cf7ad43e963c223258070f4d36cabf to your computer and use it in GitHub Desktop.
Async in Python
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
''' | |
Calling Normal Function using Async Functions | |
1. to_thread | |
2. gather+to_thread | |
Calling ASync Function using Async Functions | |
1. No need of to_thread | |
2. only gather | |
''' | |
import asyncio | |
import threading | |
import time | |
#Normal Function | |
def normal(a): | |
print("Running normal") | |
time.sleep(a) | |
print(f"{threading.get_native_id()}") | |
print(f"done wait {a}") | |
#Async Function | |
async def asyncFn(i): | |
print("Running asyncFn") | |
await asyncio.sleep(i) | |
print(i) | |
return i | |
async def main(): | |
t1=asyncio.create_task(asyncFn(3)) | |
result1=await t1 | |
await asyncio.gather(asyncFn(3),asyncFn(1)) | |
await asyncio.to_thread(normal,1) | |
await asyncio.gather(asyncio.to_thread(normal,3),asyncio.to_thread(normal,1)) | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment