Concurrency and async · Part 23 of 36

Threads, data races and locks

Expert 20 min

Shared-memory threads, race conditions, mutexes and atomics, the Python GIL and the free-threaded build (3.13–3.14).

What you will learn

  • You can explain a race condition and fix it with a lock or an atomic operation.
  • You can describe the GIL and what Python 3.13/3.14 free-threading changes.
  • You can use workers and SharedArrayBuffer/Atomics in JavaScript.

Before this: The event loop, promises and async/await

Threads share memory

A thread is an independent flow of execution inside a process. Threads of the same process share memory, so they can work on the same data without copying — and they can corrupt it together.

Two robot arms reaching for the same box

A race condition

import threading
count = 0
def work():
    global count
    for _ in range(100_000):
        count += 1          # read, add, write — three steps

threads = [threading.Thread(target=work) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(count)                # may be less than 400000

count += 1 is not one indivisible step: two threads can both read 41, both add one, both write 42 — one increment is lost. That is a race condition: the result depends on timing. Races are nasty because they show up rarely, under load, and vanish when you add debugging output.

Locks and atomics

A mutex (lock) lets only one thread at a time into a critical section:

lock = threading.Lock()
def work():
    global count
    for _ in range(100_000):
        with lock:
            count += 1

Locks cost time and bring new dangers:

  • Deadlock: thread 1 holds lock A and waits for B; thread 2 holds B and waits for A. Prevent it by always taking locks in the same global order.
  • Contention: many threads waiting for one lock run no faster than one thread.

Atomic operations (compare-and-swap, atomic add) update a single value indivisibly without a lock, using special CPU instructions. They are the basis of lock-free data structures — hard to get right; use the library ones.

Python: the GIL and free-threading

CPython has long had a Global Interpreter Lock (GIL): only one thread executes Python bytecode at a time. Threads still help for I/O-bound work (they release the GIL while waiting), but CPU-bound Python code got no speed-up from threads; people used multiprocessing instead. (Note: the GIL never made count += 1 safe — the race above can still happen with the GIL.)

PEP 703 made the GIL optional. Python 3.13 (October 2024) shipped an experimental free-threaded build; with Python 3.14 (October 2025) it became officially supported (PEP 779), though still a separate build and not the default as of late 2026. In it, threads really run Python code in parallel — and code that relied on the GIL's accidental protection must use proper locks. Single-threaded code runs somewhat slower in the free-threaded build, and C extensions must declare support.

JavaScript: workers

JavaScript keeps one thread per event loop and offers workers for parallelism: Web Workers in browsers, worker_threads in Node.js. Workers normally share nothing and communicate by message passing (postMessage), so data races can't happen. For high-performance cases, a SharedArrayBuffer gives them shared memory and Atomics gives atomic operations and waiting — browsers only allow it on cross-origin-isolated pages (since the Spectre attacks of 2018).

Memory models

On modern CPUs, a write by one core is not instantly visible to others, and compilers and CPUs reorder instructions. A language's memory model (Java since 2004, C++11, the ECMAScript memory model for SharedArrayBuffer) defines which reorderings are allowed and how locks and atomics create "happens-before" order. The practical rule: shared mutable data must be protected by a lock or accessed atomically — "it worked in testing" proves nothing.

Key points

  • Threads share memory; unsynchronised read–modify–write sequences cause race conditions.
  • Mutexes protect critical sections; take locks in a fixed order to avoid deadlocks.
  • Atomic operations update single values indivisibly; prefer library implementations.
  • CPython's GIL blocks parallel bytecode; free-threaded builds arrived in 3.13 (experimental) and became supported in 3.14.
  • JavaScript uses workers with message passing; SharedArrayBuffer + Atomics need cross-origin isolation.

Flashcards

Question: Why can count += 1 lose updates with threads?
Answer: It is a read, an add and a write; two threads can interleave between them.
Question: How do you prevent deadlocks with several locks?
Answer: Always acquire them in the same global order.
Question: What did Python 3.14 change about free-threading?
Answer: The free-threaded (no-GIL) build became officially supported (PEP 779), still optional.
Question: How do Web Workers normally communicate?
Answer: By message passing with postMessage — no shared memory.

Check yourself

Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.

  1. Four threads each add 1 to a shared counter 100,000 times without a lock. What can the final value be?

    • 400,000 or less
    • Always exactly 400,000
    • Always more than 400,000
    • Always 100,000
    Show the answer

    400,000 or less

    Lost updates make the result at most 400,000, often less.

    Source: OSTEP, ch. 26 Concurrency: An Introduction

  2. Thread 1 holds lock A and waits for B; thread 2 holds B and waits for A. This is…

    • a deadlock
    • a race condition
    • a memory leak
    • a livelock
    Show the answer

    a deadlock

    Each waits forever for the other — a deadlock.

    Source: OSTEP, ch. 32 Common Concurrency Problems

  3. Which statements about CPython are true as of late 2026?

    • Free-threaded builds exist since Python 3.13
    • The free-threaded build is officially supported since 3.14
    • The GIL made count += 1 thread-safe
    • The default build still has a GIL
    Show the answer

    Free-threaded builds exist since Python 3.13; The free-threaded build is officially supported since 3.14; The default build still has a GIL

    PEP 703/779: experimental in 3.13, supported in 3.14, still optional. The GIL never made compound operations atomic.

    Source: PEP 703, PEP 779

  4. In JavaScript, SharedArrayBuffer is used together with the ___ object for atomic operations.

    Show the answer

    Atomics

    Atomics provides atomic read-modify-write and wait/notify on shared memory.

    Source: MDN, Atomics

Sources

Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.