Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Calendar in Python
Next article icon

asyncio in Python

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
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.

Next Article
Calendar in Python

Z

zehraina
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Python Modules
    Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work. In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we
    7 min read
  • Python Arrays
    Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences: Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
    10 min read
  • asyncio in Python
    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, databa
    4 min read
  • Calendar in Python
    Python has a built-in Python Calendar module to work with date-related tasks. Using the module, we can display a particular month as well as the whole calendar of a year. In this article, we will see how to print a calendar month and year using Python. Calendar in Python ExampleInput: yy = 2023 mm =
    2 min read
  • Python Collections Module
    The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
    13 min read
  • Working with csv files in Python
    Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data. In article explains What is CSV. Working with CSV files in Python, Rea
    10 min read
  • Python datetime module
    In Python, date and time are not data types of their own, but a module named DateTime in Python can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. In this article, we will explore How DateTime in Python
    14 min read
  • Functools module in Python
    Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes - partial and partialmethod. Partial class A partial function
    6 min read
  • hashlib module in Python
    A Cryptographic hash function is a function that takes in input data and produces a statistically unique output, which is unique to that particular set of data. The hash is a fixed-length byte stream used to ensure the integrity of the data. In this article, you will learn to use the hashlib module
    5 min read
  • Heap queue or heapq in Python
    A heap queue or priority queue is a data structure that allows us to quickly access the smallest (min-heap) or largest (max-heap) element. A heap is typically implemented as a binary tree, where each parent node's value is smaller (for a min-heap) or larger (for a max-heap) than its children. Howeve
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences