DEV Community

Cover image for Perform multiple tasks concurrently in Python: "Asynchronous Programming in Python with Asyncio"
Anurag Verma
Anurag Verma

Posted on • Edited on

5

Perform multiple tasks concurrently in Python: "Asynchronous Programming in Python with Asyncio"

Asyncio is a Python library for writing asynchronous code. Asynchronous programming allows a program to perform multiple tasks concurrently, rather than waiting for one task to be complete before starting the next. This can be useful for improving the performance of programs that perform tasks that take a long time to complete, such as making network requests or reading and writing to a database.

Asyncio uses the async/await syntax to define asynchronous functions and to pause and resume them as needed. Here's a simple example of an asynchronous function that uses asyncio to pause and wait for a delay:

import asyncio

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print("started")
    await say_after(1, "hello")
    await say_after(2, "world")
    print("completed")

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

This code will print "started", then "hello" after a delay of 1 second, followed by "world" after a delay of 2 seconds. Finally, it will print "completed". Asyncio allows the program to perform other tasks while waiting for the delays to complete, rather than blocking until they are finished.

I hope you liked it!

Buy Me A Coffee

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (2)

Collapse
 
johntellsall profile image
John Mitchell

clear and useful, thanks!

Collapse
 
anurag629 profile image
Anurag Verma

🖐️ thanks @johntellsall follow for such more content.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay