Skip to the workspace
Pebellslearn by building
Frameworks & Tooling  ›  Lesson

Threads and the GIL

Threading 30 minThreads are execution paths that share a process’s memory. In GIL-enabled CPython, the global interpreter lock permits one thread per interpreter to execute Python bytecode at a time.

Threads are execution paths that share a process’s memory. In GIL-enabled CPython, the global interpreter lock permits one thread per interpreter to execute Python bytecode at a time.

Distinguish waiting from CPU work and protect multi-step shared-state changes rather than assuming the interpreter lock makes them atomic.

Three downloads can overlap their waiting time, while three pure-Python calculations on a GIL-enabled CPython build still compete for Python execution. Start by identifying the bottleneck. Then inspect a lost update and the shared invariant a lock must protect. Real thread labs run locally; the browser exercise simulates a supplied schedule.

One door, the GIL: thread A is inside running Python bytecode while threads B and C wait outside. A thread doing a slow network wait releases the lock so another can run; pure number-crunching only takes turns when the interpreter forces a switch

Wait for a slow download, not block on it

Threads earn their keep when most of the time is spent waiting, not computing — three downloads waiting on the network can all be "in flight" at once, because each one releases the GIL the moment it's waiting on the network, not the CPU:

import threading
import time

def download(name, seconds):
    time.sleep(seconds)          # simulates waiting on the network
    print(f"{name} done")

threads = [threading.Thread(target=download, args=(f"file{i}", 1)) for i in range(3)]
for t in threads:
    t.start()
for t in threads:
    t.join()                     # wait for every thread to finish
# the three sleeps overlap, so completion is around 1 second total —
# each sleep() releases the GIL while it waits

t.start() launches the thread; t.join() blocks the main thread until that one finishes. Three 1-second waits finish in about 1 second total, not 3, because while one thread sleeps, another can run.

Preparing this topic’s interactive investigation…

Crunch numbers across 4 threads

For pure-Python CPU-bound work on GIL-enabled CPython, this pattern does not provide parallel Python execution — there's no waiting to overlap, only computing, and the GIL only lets one thread compute at a time:

import threading

def count_to(n):
    total = 0
    for i in range(n):
        total += 1
    return total

threads = [threading.Thread(target=count_to, args=(50_000_000,)) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
# four threads, but still only ONE running Python bytecode at any instant —
# this takes roughly as long as running count_to four times in a row

This is the one-line test for "will threads help here?" — does the work spend most of its time waiting, or computing? Waiting may be overlapped if the operation releases the GIL. For pure-Python computation on a GIL-enabled build, consider processes; native code and free-threaded builds require their own measurements.

Lose an update to a shared counter

A read/modify/write operation can have a race when its steps are allowed to interleave. Exact switching opportunities vary by CPython version and operation; repeatedly running counter += 1 is not a reliable way to force a demonstration. This local example deliberately synchronizes both reads before either write:

import threading

counter = 0
both_read = threading.Barrier(2)

def increment():
    global counter
    local = counter
    both_read.wait()  # both workers have read the initial zero
    counter = local + 1

threads = [threading.Thread(target=increment) for _ in range(2)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()
print(counter)  # 1: two attempted increments, one final update

Both threads read the same old value before either writes the new one, so one increment vanishes. A Lock protects the complete update region from other users of that lock — only one thread can hold the lock at a time:

lock = threading.Lock()

def safe_increment():
    global counter
    for _ in range(100_000):
        with lock:          # only one thread inside this block at a time
            counter += 1

with lock: makes the read-add-write region mutually exclusive among workers that acquire that same lock. Exactly which interleavings happen is up to the OS scheduler and never guaranteed — but the pattern of a lost update is something you can compute by hand, for an exact, chosen interleaving.

python

Measure the bottleneck and protect the invariant

“Uses threads” is not a performance explanation. Split elapsed time into work that computes, work waiting on an external resource, and coordination overhead. If downloading takes 900 ms and parsing takes 100 ms, overlapping waits may help. If parsing dominates, adding download threads will soon stop helping. Measure the actual workload, including startup and result collection.

The GIL statement is specific to a GIL-enabled CPython build and Python execution. Some native extensions release the GIL during computation. CPython 3.13 introduced an experimental free-threaded build; 3.14 continues that optional build separately from the default GIL-enabled build. Extension compatibility and whether the GIL is enabled at runtime still matter. “Threads cannot parallelize any computation” is therefore too broad.

Synchronization protects a program invariant, not a particular bytecode story. Suppose stock starts at 1 and two workers both check stock > 0 before decrementing. The invariant is “at most one order reserves the final item”. Protect the check and decrement together, or move ownership to one worker receiving messages. Locking only the assignment is too late.

A lock does not make its holder uninterruptible: the OS may pause it. It prevents other participants using the same lock from entering the protected section simultaneously. Keep slow I/O outside the critical section when the invariant permits it. A thread that ignores the lock is not protected by another thread's good behavior.

Local investigation: compare one worker with a small fixed pool on controlled I/O and CPU workloads, then report elapsed time and total work completed. Avoid claiming an exact speedup from simulated sleeps. The browser schedule exercise is an authored interleaving model: it proves what follows from the supplied read/increment/write order, not which bytecode switches your installed CPython will perform.

References: threading and locks, 3.13 free threading, and 3.14 free threading.

Quick practice

quick drill

Assuming independent 1-second waits, enough network capacity and negligible processing overhead, a function downloads 10 pages sequentially. Will running it with 10 threads instead of 1 make it roughly 10x faster?

What does this print?
def final_value(schedule, start=0):
    shared = start
    locals_ = {}
    for thread, step in schedule:
        if step == "read":
            locals_[thread] = shared
        elif step == "incr":
            locals_[thread] = locals_[thread] + 1
        elif step == "write":
            shared = locals_[thread]
    return shared

schedule = [["A", "read"], ["A", "incr"], ["B", "read"], ["A", "write"], ["B", "incr"], ["B", "write"]]
print(final_value(schedule))
What does this print?
def final_value(schedule, start=0):
    shared = start
    locals_ = {}
    for thread, step in schedule:
        if step == "read":
            locals_[thread] = shared
        elif step == "incr":
            locals_[thread] = locals_[thread] + 1
        elif step == "write":
            shared = locals_[thread]
    return shared

schedule = [["A", "read"], ["A", "incr"], ["A", "write"], ["A", "read"], ["A", "incr"], ["A", "write"]]
print(final_value(schedule))
quick drill

On GIL-enabled CPython, four threads each sum 10 million numbers purely in Python (no I/O at all). Compared to doing the same work in one thread, four threads will be about how much faster?


🎯 Your turn

Write final_value(schedule, start=0). schedule is a list of [thread_id, step] pairs, where step is "read", "incr", or "write". Each thread has its own local value: "read" copies the shared counter into that thread's local; "incr" adds one to the local; "write" copies the local back into the shared counter. Simulate the schedule in order and return the final shared value.

  • final_value([["A","read"],["A","incr"],["A","write"],["B","read"],["B","incr"],["B","write"]]) → 2
  • final_value([["A","read"],["B","read"],["A","incr"],["B","incr"],["A","write"],["B","write"]]) → 1 (a lost update)

Hint: keep a dict of each thread's local value, updating it on "read" and "incr", and only touch the shared value on "write".

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below builds tools for spotting and avoiding the race this function can produce.

Your task
Write final_value(schedule, start=0). schedule is a list of [thread_id, step] pairs where step is "read", "incr" or "write". Each thread has its own local value: "read" copies the shared counter into that thread's local, "incr" adds one to the local, "write" copies the local back into the shared counter. Simulate the schedule in order and return the final shared value. Example: a schedule where A fully finishes before B starts gives 2; an interleaved schedule where both read before either writes gives 1 (a lost update).

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upApply one step

Write apply_step(shared, local, step) for a SINGLE thread. step is "read", "incr" or "write". Return [new_shared, new_local] after applying it.

concurrency
DrillRun one thread uninterrupted

Write run_steps(start, steps). A single thread runs every step in steps in order, with nothing else interleaved. Return the final shared value.

concurrency
BuildDetect a risky schedule

Write is_interleaved(schedule). schedule is a list of [thread_id, step] pairs. Return True if the thread ids are NOT grouped into contiguous blocks — i.e. a thread appears again after a DIFFERENT thread has already run at least one step.

concurrency
BossCount the lost updates

Write lost_updates(schedule). Every "incr" step represents one attempted increment, starting from 0. Return how many of those increments never made it into the final shared value — (number of incr steps) - final_value(schedule).

concurrency
CapstoneBuild a schedule with no race

Write make_safe_schedule(threads). Given a list of thread ids, build a schedule where each thread fully completes "read", "incr", "write" before the next thread starts — guaranteed never to lose an update, no matter how many threads.

concurrency
Project context and further resources
final_value.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
final_value(schedule, start) → intSimulate a schedule of read/incr/write steps across threads sharing one counter, and return the final counter value.
try:
returned
No app map for this section yet.
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.