Concurrent Execution

The modules described in this chapter provide support for concurrent execution of code. The appropriate choice of tool will depend on the task to be executed (CPU bound vs IO bound) and preferred style of development (event driven cooperative multitasking vs preemptive multitasking). Here’s an overview:

What the program does

Default build

Free-threaded build

Calls blocking functions, such as file or database access

Threads

Threads

Waits on many network connections, or needs cancellation and timeouts

asyncio

asyncio

CPU-bound work in native code that releases the global interpreter lock

Threads

Threads

CPU-bound work in Python code

multiprocessing or concurrent.interpreters

Threads

Work that shares little data or needs isolation

multiprocessing or concurrent.interpreters

multiprocessing or concurrent.interpreters

In an asyncio program, use asyncio.to_thread() for the work the table assigns to threads. Calling a blocking function directly stalls the event loop, even if the function releases the global interpreter lock.

The modules listed below provide these tools, along with lower-level building blocks such as queue and contextvars. asyncio is documented in Networking and Interprocess Communication.

The following are support modules for some of the above services: