Asynchronous Programming using asyncio in Python
Asynchronous is a programming feature to perform different tasks at the same time without having to wait for one task to complete to run another task.
Asynchronous code is useful when we want to perform multiple operations simultaneously and complete tasks faster. Asynchronous is well suited for network operations such as to make API calls or download files from the internet, read/write data to files or databases, etc. It is also suited for CPU intensive operations such as performing thousands of complex processing within a loop, etc.
Asynchronous programming can help to improve application performance. In Python, we can use the asyncio library to write an asynchronous program.
asyncio is a standard Python module that was added to Python 3.4. asyncio uses async/await syntax. The async keyword makes a function asynchronous and also allows the use of await keyword inside the function body.
Difference Between Concurrency, Parallelism, Threading, and Asyncio
Concurrency is when a program runs multiple different tasks simultaneously in an overlapping manner.
Parallelism is running of multiple tasks simultaneously on multiple processors.
Threading is a programmming technique to run multiple tasks simultaneously on a single processor.
Asyncio is short for asynchronous input/output. Asynchronous code means to be able to perform different I/O operations simultaneously without blocking one task to run another task.
The following snippet of code prints Download started- filename, awaits 2 seconds and then prints Download Completed- filename:
import asyncio
import time
async def some_download(filename):
print("Download started- ", filename)
await asyncio.sleep(2)
print("Download Completed- ", filename)
async def main():
await asyncio.gather(some_download("file_1.csv"), some_download("file_2.csv"), some_download("file_3.csv"))
if __name__ == "__main__":
start_time = time.perf_counter()
asyncio.run(main())
time_taken = time.perf_counter() - start_time
print(f"Completed in {time_taken:0.2f} seconds.")
Output:
Download started- file_2.csv
Download started- file_3.csv
Download Completed- file_1.csv
Download Completed- file_2.csv
Download Completed- file_3.csv
Completed in 2.00 seconds.