The Wayback Machine - https://web.archive.org/web/20240616135542/https://www.geeksforgeeks.org/asyncio-in-python/
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.


Previous Article
Next Article

Similar Reads

How to create telnet client with asyncio in Python
Telnet is a client/server application protocol that uses TCP/IP for connection. Telnet protocol enables a user to log onto and use a remote computer as though they were connected directly to it within the local network. The system that is being used by the user for the connection is the client and the remote computer being connected is the server.
4 min read
Python Taskgroups with asyncIO
In this article, we will see the use of Task Groups with asyncIO in Python. What is a Task group? Task groups are introduced in Python 3.11 along with Exception Groups and as the name suggests it groups similar or different tasks together. It is already possible using the gather() method of asyncio module, but the problem with it is that if there i
6 min read
Asyncio Vs Threading In Python
In Python, both Asyncio and Threading are used to achieve concurrent execution. However, they have different mechanisms and use cases. This article provides an in-depth comparison between Asyncio and Threading, explaining their concepts, key differences, and practical applications. Table of Content Key Differences Between Asyncio and ThreadingUnder
4 min read
Periodically Execute a Function with asyncio in Tornado
The primary benefit is improved performance. Asynchronous programming allows your application to efficiently handle tasks that may block the main thread, such as network operations or I/O-bound tasks. This can lead to better responsiveness and scalability. Also by controlling the frequency of periodic tasks in Tornado, you can control the frequency
4 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Article Tags :
Practice Tags :