This tutorial was written in 2019. Python and library APIs may need changes to run these examples today.
What is asynchronous work?
Imagine running ten washing machines and boiling water in ten kettles. One method is to start the first machine, wait for it to finish, collect the laundry, and repeat for every machine. Then start each kettle in turn, wait for it, and make tea.
Another method is to start the machines and kettles without waiting for each one to finish, then collect the laundry or make tea as each task completes. The second method overlaps waiting periods with other work.
The first is a synchronous way to organize the tasks; the second illustrates asynchronous work. Similarly, an asynchronous program can start other work while waiting for a response, whereas a synchronous sequence waits before moving on.
Threads and asynchronous work
The following analogy is simplified. In real CPython, threads can overlap while waiting for I/O and may release the GIL; the operating system schedules them. Whether threads or asynchronous I/O are more efficient depends on the workload and environment.
Imagine assigning one person to each washing machine. In the analogy, only one person acts at a time: each starts a machine, hands control to the next person, and eventually checks whether their machine is done. Passing control and checking unfinished work can add overhead, and a finished task may wait until its assigned person can collect it.
For tasks that spend time waiting on responses, such as network I/O, asynchronous programming can help overlap those waits. Threads can also overlap I/O; the right approach depends on the application.
The next post uses Python code to explore asyncio.