Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Advanced Python & Software Engineering — Alpha School

Lesson 18: Processes and asyncio

Threads share memory, which makes them fast to start but dangerous to share. Processes are the opposite: each process has its own memory and its own Python interpreter — and its own GIL. That means processes can truly run Python code in parallel on multiple CPU cores, which is exactly what threads cannot do. The multiprocessing module gives you processes with an interface deliberately similar to threading, and the example below squares a list of numbers across a pool of worker processes. For CPU-heavy work, this is the tool that actually makes things faster.

The price of processes is that they cannot share memory directly. Data has to be sent between processes — pickled, sent through a pipe, and unpickled on the other side — which costs time, and means the data must be picklable. A Pool handles most of this for you: you hand it a function and a list of inputs, and it distributes the work and collects the results. As a rough guide, use processes when the work is heavy enough that the cost of sending data is small compared with the computation itself.

from multiprocessing import Pool


def square(n):
    return n * n


if __name__ == "__main__":
    with Pool(4) as pool:
        print(pool.map(square, [1, 2, 3, 4, 5]))
        # [1, 4, 9, 16, 25] — computed across 4 worker processes

asyncio: one thread, many waiting tasks

There is a third way to do several things at once, and it is increasingly the one Python programmers reach for: asyncio. Instead of threads or processes, you write async def functions — coroutines — and the program switches between them at points you mark with await. While one task awaits a download, another runs. Everything happens in a single thread, so there are no race conditions and no GIL worries, and you can juggle thousands of connections with very little memory. The catch is that the code must be written in the async style throughout: a blocking call inside a coroutine blocks everything.

import asyncio


async def fetch(name, delay):
    await asyncio.sleep(delay)  # pretend to wait for a download
    return f"{name} done"


async def main():
    results = await asyncio.gather(
        fetch("a", 0.2), fetch("b", 0.1), fetch("c", 0.15))
    print(results)


asyncio.run(main())

Choosing between the three is a matter of the job. Threads are the simplest fit for a small amount of I/O-bound work in an ordinary program. Processes are the fit for CPU-bound work that needs real parallelism. asyncio is the fit for a program that juggles many I/O operations at once — a web server, a chat client, a scraper — and is willing to be written in the async style from the start. Many real systems mix them: an asyncio server that hands heavy computation to a process pool. The important thing is to name the kind of work first, and only then pick the tool.

Going further

The concurrent.futures module from the last lesson is also the bridge between the three styles of concurrency. An asyncio program can hand CPU-heavy work to a process pool with loop.run_in_executor, so the event loop stays responsive while the heavy work runs on another core. That combination — asyncio for waiting, processes for computing — is how many real servers are built. The lesson is that threads, processes and coroutines are not rivals; they are tools that compose, and the best designs use each where it fits.

One more asyncio idea is worth meeting: the event loop itself. When you call asyncio.run(main()), Python creates an event loop, runs your coroutine, and switches between tasks whenever one awaits something. A task that never awaits — one that crunches numbers in a tight loop — blocks the whole loop, and no other task can run. That is the single most important rule of asyncio: never block the loop. Long computations belong in an executor, and blocking calls belong in a thread. Follow that rule, and asyncio will handle thousands of connections with ease.

To feel the difference between the three styles, try the same job three ways: download the contents of five web addresses, first one after another, then with threads, then with asyncio. The sequential version takes the sum of the five waiting times; the threaded and async versions take roughly the longest single wait. The numbers will depend on your connection, so treat them as an illustration rather than a measurement — but the shape of the result is the lesson. And notice what each version costs you: threads add shared-state risk, asyncio adds the async style throughout, and the sequential version costs only time.

Key Terms

Process
An independent running program with its own memory and interpreter; several processes run truly in parallel.
multiprocessing
The standard-library module for running work in separate processes.
Pool
A group of worker processes that distributes tasks and collects results, such as pool.map().
asyncio
The standard-library framework for writing concurrent code with async def functions and await.
Coroutine
An async def function; it can pause at await and resume later without blocking the program.
await
The keyword that pauses a coroutine until the awaited operation finishes, letting other tasks run.
asyncio.gather()
Runs several coroutines at the same time and collects their results in order.
Pickling
Converting a Python object to bytes so it can be sent between processes.

Discussion Questions

  1. Why can processes speed up number-crunching while threads cannot? What does each process have that a thread does not?
  2. What is the cost of using processes instead of threads? When would that cost outweigh the benefit?
  3. asyncio has no race conditions but requires the async style throughout. Why is one blocking call inside a coroutine so damaging?

Practice Questions

  1. What does pool.map(square, [1, 2, 3, 4, 5]) return?
  2. Why is the if __name__ == "__main__": guard needed with multiprocessing?
  3. What does await asyncio.sleep(0.2) do?
  4. A web server handles 1,000 simultaneous connections, mostly waiting. Which tool fits best?
  5. Name one thing processes cannot do that threads can.
Show answers
  1. [1, 4, 9, 16, 25]. The pool distributes the squaring across its workers and returns the results in order.
  2. So worker processes do not re-run the top-level code when they start. On some platforms workers re-import the module; without the guard they would spawn more workers forever.
  3. It pauses this coroutine for 0.2 seconds while other tasks run. Unlike time.sleep, it does not block the whole program.
  4. asyncio. Thousands of coroutines in one thread use far less memory than thousands of threads, with no race conditions.
  5. Share memory directly. Data must be pickled and sent between processes, which costs time and limits what can be passed.
Keep reading to complete this lesson