Skip to content
Fullstack Launchpad

Python Concurrency: GIL, Threads, Processes and asyncio #4.2

While one task waits for I/O, another can run. When most of the work is Python computation, separate processes can use multiple CPU cores.

By Published Updated 8 min readPython for Engineers Switching Languages

When does the work start?

What does this code print? Look at the list just after the line job = reply().

python
import asyncio

seen = []

async def reply():
    seen.append("Orbit")
    return "ready"

job = reply()
print(seen)
# prints: []
print(asyncio.run(job))
# prints: ready
print(seen)
# prints: ['Orbit']

Calling a function declared with async def creates a coroutine, a call that can suspend and resume. Something still has to run its body. Here, asyncio.run(job) starts an event loop, the scheduler that runs the coroutine to completion, then closes the loop.

The choice throughout this lesson is where the next piece of work should run. A request waiting for the network can give another request a turn. A loop calculating pixel values keeps its thread busy.

SectionExampleResult
The GIL and threadsrows['Orbit', 'ready']
CPU work in processessquares[9, 16]
Waiting for several coroutinesanswers['first', 'second']
Failure in a groupsibling.cancelled()True
Time limitsawait pending.wait()Deadline expires
Blocking I/Oawait route()True
LLM request limitslen(answers)50

How some other languages compare

OperationJSJavaGo
Wait for a resultawaitFuture.get()Receive from a channel
Run CPU work on another coreWorkerExecutorServiceStart a goroutine with go

The GIL and threads

Two threads in one process share memory. In a default CPython build, the global interpreter lock (GIL) allows one thread at a time to execute Python bytecode in a given interpreter. Bytecode is the set of instructions the interpreter executes after compiling the source.

CPython can release the GIL while a thread waits for I/O, such as a file read. Another thread can run during that wait. Here a pool of up to two threads reads two files. Even if the second read finishes first, pool.map returns the results in the order of the input files.

python
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    files = [Path(folder) / name for name in ("bot", "state")]
    files[0].write_text("Orbit")
    files[1].write_text("ready")
    with ThreadPoolExecutor(max_workers=2) as pool:
        rows = list(pool.map(Path.read_text, files))

print(rows)
# prints: ['Orbit', 'ready']

The GIL doesn't reserve a thread across several steps, such as checking a balance and then deducting a payment. If multiple threads update shared state this way, protect the whole operation with the same lock.

CPython has offered a free-threaded build since 3.13. With the GIL disabled, multiple threads can execute bytecode on multiple cores. The version number alone doesn't tell you whether the GIL is active.

Splitting a calculation across processes

Suppose you need to resize 10,000 images with a pixel loop written in Python. Split the images into batches and give each process a batch. Each process has its own interpreter and memory. A worker can open an image by path so the caller only has to send a filename. If the imaging library releases the GIL in native code, threads can use multiple cores too. Measure with the library and image sizes you actually use.

This smaller example squares two numbers. pool.map(pow, bases, powers) pairs each base with the exponent at the same position. The guard at the bottom of the file keeps a child process from starting another pool when it imports the module.

python
from concurrent.futures import ProcessPoolExecutor

if __name__ == "__main__":
    with ProcessPoolExecutor(max_workers=2) as pool:
        squares = list(pool.map(pow, [3, 4], [2, 2]))

    print(squares)
    # prints: [9, 16]

Waiting for coroutines with gather

For 100 requests to a large language model (LLM), the network and the remote server may account for most of the wait. For 10,000 mostly idle WebSocket connections, an event loop with async I/O also fits. A connection needs execution time only when it has work to do.

SyntaxMeaning
await ready.wait()If the signal hasn't arrived, suspend this task so the loop can run another.
ready.set()Signal the waiting tasks.
asyncio.gather(a, b)Schedule both coroutines and collect their results in argument order.
python
import asyncio

async def main():
    ready = asyncio.Event()
    finished = []

    async def first():
        await ready.wait()
        finished.append("first")
        return "first"

    async def second():
        finished.append("second")
        ready.set()
        return "second"

    answers = await asyncio.gather(first(), second())
    print(finished)
    # prints: ['second', 'first']
    print(answers)
    # prints: ['first', 'second']

asyncio.run(main())

A task is the object the loop uses to drive a scheduled coroutine. Here, second must signal before first can finish. If you wrote await first() followed by await second(), the first call would wait forever. An await can also return immediately if its result is already available.

To consume results as they stream in, see async generators in part 2.2. For connection lifetimes with async with, see asynchronous context managers in part 3.2.

When one task in a TaskGroup fails

Suppose an answer depends on two sources. With the default gather settings, the first exception reaches the caller while the other tasks can keep running. If losing one source makes the other request pointless, use asyncio.TaskGroup (Python 3.11+).

python
import asyncio

async def reject():
    raise ValueError("bad input")

async def main():
    try:
        async with asyncio.TaskGroup() as group:
            sibling = group.create_task(asyncio.Event().wait())
            group.create_task(reject())
    except* ValueError as errors:
        print(str(errors.exceptions[0]))
        # prints: bad input
    print(sibling.cancelled())
    # prints: True

asyncio.run(main())

group.create_task adds a coroutine to the group. When reject fails, the group requests cancellation of the waiting task and waits for it to finish before leaving the block. The group collects failures in an ExceptionGroup. The except* ValueError clause handles the portion containing errors of that type. If all tasks succeed, you can read each task's .result() after leaving the block.

Setting a deadline with wait_for

A connection can stay open even when the server stops sending data. Use asyncio.wait_for to give one operation a time limit. Here, pending never receives a signal, so the outcome is the same on a fast or slow machine.

python
import asyncio

async def main():
    pending = asyncio.Event()
    try:
        await asyncio.wait_for(pending.wait(), timeout=0.01)
    except TimeoutError:
        print("timed out")
        # prints: timed out

asyncio.run(main())

At the deadline, wait_for requests cancellation and waits for the operation to handle it. The actual wait can exceed the deadline. To give several steps a single time budget, wrap them in asyncio.timeout (Python 3.11+) and catch TimeoutError outside the block.

python
import asyncio

async def main():
    try:
        async with asyncio.timeout(0.01):
            await asyncio.sleep(0)
            await asyncio.Event().wait()
    except TimeoutError:
        print("deadline reached")
        # prints: deadline reached

asyncio.run(main())

Moving blocking I/O off the loop

Calling requests.get(...) or time.sleep(...) directly inside an async def route occupies the loop's thread until the function returns. Every other connection on that loop has to wait. For a delay, use await asyncio.sleep(...). For a library that requires blocking I/O, move the call to a worker thread with asyncio.to_thread.

python
import asyncio
import threading
import time

def blocking_read():
    time.sleep(0.01)
    return threading.get_ident()

async def route():
    loop_thread = threading.get_ident()
    worker_thread = await asyncio.to_thread(blocking_read)
    return worker_thread != loop_thread

async def main():
    print(await route())
    # prints: True

asyncio.run(main())

Pass the function blocking_read itself to to_thread. Writing blocking_read() in the argument list would call it immediately on the loop's thread. With a real HTTP library, also set a client timeout. Cancelling the task waiting for a thread cannot stop a call already running in that thread.

Sending 50 prompts at 10 requests per second

Requests in flight tell you how many connections are busy at once. Starts per second measure how quickly you send requests. If each request takes just 5 ms, ten slots can turn over many times in one second.

This example uses Semaphore(3) as a local limit. Each task must acquire one of three slots before making its call. Leaving async with returns the slot. Eight coroutines are scheduled, but the peak number of active calls is three. The asyncio.sleep(0) gives other tasks a turn so you can see the limit take effect.

python
import asyncio

async def main():
    slots = asyncio.Semaphore(3)
    active = peak = 0

    async def ask():
        nonlocal active, peak
        async with slots:
            active += 1
            peak = max(peak, active)
            await asyncio.sleep(0)
            active -= 1

    await asyncio.gather(*(ask() for _ in range(8)))
    print(peak)
    # prints: 3

asyncio.run(main())

What about the provider's ten requests per second? In the next example, every attempt, including retries, passes through one lock. Starts are spaced at least 0.1 seconds apart on the loop's monotonic clock. The lock is released just before waiting for a reply, so the requests can still overlap. The example simulates one HTTP 429 response (too many requests) with a requested delay of 0.2 seconds. Testing this code with a fake client is covered in part 5.3.

python
import asyncio

class RateLimited(Exception):
    def __init__(self, retry_after):
        self.retry_after = retry_after

async def send(number, attempt):
    await asyncio.sleep(0)
    if number == 0 and attempt == 1:
        raise RateLimited(0.2)
    return number

async def main():
    loop = asyncio.get_running_loop()
    gate = asyncio.Lock()
    slots = asyncio.Semaphore(3)
    next_start = 0.0

    async def ask(number):
        nonlocal next_start
        for attempt in (1, 2):
            try:
                async with slots:
                    async with gate:
                        while (delay := next_start - loop.time()) > 0:
                            await asyncio.sleep(delay)
                        next_start = loop.time() + 0.1
                    return await send(number, attempt)
            except RateLimited as error:
                if attempt == 2:
                    raise
                await asyncio.sleep(error.retry_after)

    answers = await asyncio.gather(*(ask(n) for n in range(50)))
    print(len(answers), answers[0], answers[-1])
    # prints: 50 0 49

asyncio.run(main())

The *(...) passes each coroutine as a separate argument to gather. With nonlocal, ask can update the next start time shared by all calls in main. The assignment expression := saves the remaining wait in delay inside the condition. On waking up, the task checks the clock again before sending.

Request zero fails on its first attempt and releases its slot before retrying. The 50 prompts take 51 attempts. With a real client, read the delay from Retry-After when available and only retry transient failures when repeating the operation is safe. If several processes share a quota, they need to coordinate because each process has its own lock.

Key takeaways

  • Use threads for blocking I/O, asyncio for many waiting connections, and processes for substantial pure-Python computation.
  • Use gather for results in input order. Use TaskGroup when tasks share a lifetime and one failure should cancel the remaining work.
  • Set the deadline, the in-flight limit and the request start rate separately to match the service's constraints.

Sources