Sub topic 1
Python Threads, Processes, and the GIL
Prerequisites
Assume you can write and run Python functions, use standard-library modules, and understand with statements. You should also know that a program can have several tasks in progress at once.
Concurrency and Parallelism
Concurrency means managing multiple tasks during the same period. A single worker can switch between tasks when one task is waiting. Parallelism means performing multiple tasks at the same moment, usually on different CPU cores.
For example, a program can start downloading several files concurrently. If one download waits for the network, another can use the available time. True parallelism matters when several tasks actively calculate results.
I/O-Bound and CPU-Bound Work
I/O-bound work spends much of its time waiting for input or output, such as network responses, files, or databases. CPU-bound work spends most of its time calculating.
| Workload | Main delay | Common first choice |
|---|---|---|
| I/O-bound | Waiting for external systems | Threads or asyncio |
| CPU-bound | Calculating on the processor | Processes |
The workload matters more than the number of tasks. Five network waits may overlap well, while five large calculations may compete for the same interpreter resources.
Running Tasks in Threads
A thread is a path of execution inside a process. Threads share the process's memory, so they can communicate easily. This also means they can interfere with shared data.
import time
from concurrent.futures import ThreadPoolExecutor
def fetch(number):
time.sleep(1) # Simulate network waiting.
return number * 2
with ThreadPoolExecutor(max_workers=3) as pool:
results = list(pool.map(fetch, range(3)))
print(results)The three waits can overlap, so this usually takes about one second rather than three. The exact time depends on the system.
Shared State, Race Conditions, and Locks
A race condition occurs when a result depends on the timing of competing threads. Even counter += 1 involves multiple steps. A lock allows only one thread at a time to enter a protected section.
import threading
counter = 0
lock = threading.Lock()
def add_many():
global counter
for _ in range(10_000):
with lock:
counter += 1
threads = [threading.Thread(target=add_many) for _ in range(4)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(counter)Exercise
Which model fits several tasks that mostly wait for network responses?
Show answer
Threads or asyncio, because the tasks are I/O-bound.