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 |
|
|---|---|---|
Calls blocking functions, such as file or database access |
Threads |
Threads |
Waits on many network connections, or needs cancellation and timeouts |
||
CPU-bound work in native code that releases the global interpreter lock |
Threads |
Threads |
CPU-bound work in Python code |
Threads |
|
Work that shares little data or needs isolation |
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.
threading— Thread-based parallelismmultiprocessing— Process-based parallelism- Introduction
- Reference
- Programming guidelines
- Examples
multiprocessing.shared_memory— Shared memory for direct access across processes- The
concurrentpackage concurrent.futures— Launching parallel tasksconcurrent.interpreters— Multiple interpreters in the same processsubprocess— Subprocess managementsched— Event schedulerqueue— A synchronized queue classcontextvars— Context Variables
The following are support modules for some of the above services: