Open In App

asyncio in Python

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Asyncio is a Python library that is used for concurrent programming, including the use of async iterator in Python. It is not multi-threading or multi-processing. Asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web servers, database connection libraries, distributed task queues, etc

Asynchronous Programming with Asyncio in Python

In the example below, we’ll create a function and make it asynchronous using the async keyword. To achieve this, an async keyword is used. The program will wait for 1 second after the first print statement is executed and then print the next print statement and so on. Note that we’ll make it sleep (or wait) with the help of await asyncio.sleep(1) keyword, not with time.sleep(). To run the program, we’ll have to use the run() function as it is given below. This asynchronous approach is a fundamental concept in Python programming and is particularly useful when working with async iterators in Python.

Python3




import asyncio
 
async def fn():
    print('This is ')
    await asyncio.sleep(1)
    print('asynchronous programming')
    await asyncio.sleep(1)
    print('and not multi-threading')
 
asyncio.run(fn())


Output:

asyncio in Python

Async Event Loop in Python

In the program below, we’re using await fn2() after the first print statement. It simply means to wait until the other function is done executing. So, first, it’s gonna print “one,” then the control shifts to the second function, and “two” and “three” are printed after which the control shifts back to the first function (because fn() has done its work) and then “four” and “five” are printed. This interaction demonstrates the principles of asynchronous programming, which are especially relevant when working with async iterators in Python.

Python3




import asyncio
 
async def fn():
     
    print("one")
    await asyncio.sleep(1)
    await fn2()
    print('four')
    await asyncio.sleep(1)
    print('five')
    await asyncio.sleep(1)
 
async def fn2():
    await asyncio.sleep(1)
    print("two")
    await asyncio.sleep(1)
    print("three")
asyncio.run(fn())


Output:

Now if you want the program to be actually asynchronous, In the actual order of execution we’ll need to make tasks in order to accomplish this. This means that the other function will begin to run anytime if there is any free time using asyncio.create_task(fn2())

Python3




import asyncio
async def fn():
    task=asyncio.create_task(fn2())
    print("one")
    #await asyncio.sleep(1)
    #await fn2()
    print('four')
    await asyncio.sleep(1)
    print('five')
    await asyncio.sleep(1)
 
async def fn2():
    #await asyncio.sleep(1)
    print("two")
    await asyncio.sleep(1)
    print("three")
     
asyncio.run(fn())



Example of Asyncio in Python

Output

I/O-bound tasks using asyncio.sleep()

In this example, the func1(), func2(), and func3() functions are simulated I/O-bound tasks using asyncio.sleep(). They each “wait” for a different amount of time to simulate varying levels of work.

When you run this code, you’ll see that the tasks start concurrently, perform their work asynchronously, and then complete in parallel. The order of completion might vary depending on how the asyncio event loop schedules the tasks. This asynchronous behavior is fundamental to understanding how to manage tasks efficiently, especially when working with async iterators in Python.

Python




import asyncio
 
 
async def func1():
    print("Function 1 started..")
    await asyncio.sleep(2)
    print("Function 1 Ended")
 
 
async def func2():
    print("Function 2 started..")
    await asyncio.sleep(3)
    print("Function 2 Ended")
 
 
async def func3():
    print("Function 3 started..")
    await asyncio.sleep(1)
    print("Function 3 Ended")
 
 
async def main():
    L = await asyncio.gather(
        func1(),
        func2(),
        func3(),
    )
    print("Main Ended..")
 
 
asyncio.run(main())


Output:

Output

Difference Between Asynchronous and Multi-Threading Programming 

  • Asynchronous programming allows only one part of a program to run at a specific time.
  • Consider three functions in a Python program: fn1(), fn2(), and fn3().
  • In asynchronous programming, if fn1() is not actively executing (e.g., it’s asleep, waiting, or has completed its task), it won’t block the entire program.
  • Instead, the program optimizes CPU time by allowing other functions (e.g., fn2()) to execute while fn1() is inactive.
  • Only when fn2() finishes or sleeps, the third function, fn3(), starts executing.
  • This concept of asynchronous programming ensures that one task is performed at a time, and other tasks can proceed independently.
  • In contrast, in multi-threading or multi-processing, all three functions run concurrently without waiting for each other to finish.
  • With asynchronous programming, specific functions are designated as asynchronous using the async keyword, and the asyncio Python library helps manage this asynchronous behavior.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads