Python · Module 9 · Lesson 31 min read

Multithreading & Multiprocessing

Concurrency vs parallelism

  • Concurrency juggles many tasks by switching between them; great when tasks wait (network, disk).
  • Parallelism runs tasks at the same time on several CPU cores; needed for heavy calculation.

The GIL

In standard CPython, the Global Interpreter Lock lets only one thread run Python code at a time. So:

Task typeBest tool
I/O-bound (downloads, APIs, files)threading or asyncio
CPU-bound (maths, image processing)multiprocessing

(Python 3.13 added an experimental build without the GIL, but the default still has it.)

The easy, modern API: concurrent.futures

Python
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
with ThreadPoolExecutor(max_workers=5) as pool:
    results = list(pool.map(download, urls))

Swap in ProcessPoolExecutor for CPU-heavy work. With processes, code must be under if __name__ == "__main__":.

Sharing data safely

Threads share memory, so protect shared variables with threading.Lock() to avoid race conditions.

💻 Threads and processes don't run in the in-app Python (browser sandbox). Try this on a computer.

Example

Python
import time
from concurrent.futures import ThreadPoolExecutor

def download(n):
    time.sleep(1)                 # pretend to wait for the network
    return f"file-{n}"

start = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as pool:
    results = list(pool.map(download, range(5)))
print(results)
print(f"{time.perf_counter() - start:.1f}s")   # ~1.0s instead of 5s

# Protecting shared data with a Lock
import threading

counter = 0
lock = threading.Lock()

def add_many():
    global counter
    for _ in range(100_000):
        with lock:
            counter += 1

threads = [threading.Thread(target=add_many) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(counter)                     # 400000