async & sync programing

This commit is contained in:
2025-08-23 20:00:22 +05:30
parent 0dccb17147
commit 5f642d1c10

View File

@@ -0,0 +1,83 @@
# # Normally in Python, code runs synchronously → one line after another
# # Asynchronous programming lets your program do other work while waiting for slow tasks.
# # Python provides this via the asyncio library with:
# # async def → defines an asynchronous function(coroutine)
# # await → pauses execution until an async task finishes
# # asyncio.run() → starts the event loop
import time
import asyncio
# Example 1: Normal(Synchronous)
def download_file(file_name):
print(f"Downloading file {file_name}")
time.sleep(3)
print(f"{file_name} downloaded")
def run_example_1():
download_file("file1.txt")
download_file("file2.txt")
# Example 2 Asynchronous with asyncio
async def my_task():
print("Running async task")
# we have to run the async program through the asyncio.run method its the entry point for async programs
# it's creates an event loop, runs your async function, and closes the loop
asyncio.run(my_task())
async def async_download_file(file_name):
print(f"Downloading {file_name}...")
await asyncio.sleep(2) # non-blocking wait
print(f"{file_name} downloaded")
async def call_async_fileDownload():
# With asyncio.gather(concurrent)
await asyncio.gather(
async_download_file("file_async1.txt"),
async_download_file("file_async2.txt")
)
async def call_async_fileDownload_sequential():
# sequential
await async_download_file("file_async1.txt"),
await async_download_file("file_async2.txt")
async def task(name, delay):
print(f"Starting {name}")
await asyncio.sleep(delay)
print(f"Finished {name}")
return name
async def run_at_once():
# Run both tasks at once
results = await asyncio.gather(
task("A", 1),
task("B", 5)
)
print(results) # gather function gives list of results
print(results[0])
if __name__ == "__main__":
# This will take 4 seconds (because tasks run one after another)
run_example_1()
# This will finish in ~2 seconds, because both tasks run concurrently.
asyncio.run(call_async_fileDownload())
asyncio.run(call_async_fileDownload_sequential())
asyncio.run(run_at_once())