Sunday, July 21, 2024

Async in Python

'''
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())
view raw async.py hosted with ❤ by GitHub

No comments:

Post a Comment