Better Programming

Advice for programmers.

Follow publication

Member-only story

A Hands-On Guide to Concurrency in Python With Asyncio

Michael Krasnov
Better Programming
Published in
20 min readFeb 6, 2023

--

Photo by Vadim Bogulov on Unsplash

Many of us have experienced slow websites and laggy apps at least once while programming. These issues are inherent to the design of the systems we use each day: some operations take a (relatively) long time to complete. Transferring bytes over thousands of kilometres between you and the server, reading tiny magnetic fields on the spinning disk, and other such activities may take a moment.

However, while your system is waiting for these resources, it is essential to remain usable and responsive and not waste precious CPU cycles. The concepts of concurrency and asynchronous programming were introduced to address these concerns.

“Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished.” — Mozilla

Synchronous programming, on the other hand, is when a program does all tasks strictly one after the other and will wait for extended operations to remain idle.

two images. one showing synchronous programming, the other showng asynchronous programming
Remaining images by author

Why is it so important to let the system take care of other tasks while it waits for some long IO operation? To give you some perspective, a typical 3Ghz processor can perform 30,000,000 operations in 10ms, the average time it takes for a hard drive to read some data. Imagine how wasteful our systems would be if they could not multitask!

In this article, I will teach you how to use the power of asynchronous programming in Python, using its asyncio library. We will go over some general concepts, implementation details, usage examples, and advanced capabilities of asyncio. After reading my manual, you can use asynchronous programming in Python confidently and use its capabilities in your projects.

How Async Works on the Low Level

“Asynchronous I/O is a form of input/output processing that permits other processing to continue before the…

--

--

Michael Krasnov
Michael Krasnov

Written by Michael Krasnov

Software Developer | Writer | Open Source Evangelist

Responses (3)

Write a response