unrust

Python race condition: 4 you can reproduce

Published

By the Unrust team · 9 min read · Editorial method

Python race condition on 9 builds: counter += 1 lost updates on 3.9 and free-threaded 3.14, none on 3.10 to 3.15. Run four shapes that fail everywhere.

Does the GIL prevent race conditions in Python?

The GIL does not prevent a Python race condition: a thread can still be paused between your read and your write, so read-modify-write and check-then-act code can lose data. Whether a bare counter += 1 shows it depends on the build: it lost updates on 3.9 and free-threaded 3.14 in our runs, never on 3.10 to 3.15.

The GIL protects the interpreter's own data, not your invariants. The Python docs FAQ lists the atomic operations and then says "These aren't:", naming i = i + 1 and D[x] = D[x] + 1, and it ends with "When in doubt, use a mutex!" Our runs show why that advice beats testing: the same counter loop failed on two builds and passed on seven others.

Everything below is ours: five small programs, standard library only, run on nine interpreter builds with 20 runs per cell, on one machine (8 vCPU AMD EPYC-Genoa, Linux 6.8.0-106). The fixes are our own code, and no result here says a program is safe because it passed our runs.

Read first: five snippets, which can lose data

Before you look at any result, write one line per snippet: can it lose data, and where is the gap between the read and the write? Four threads run the first two, eight threads run the cache, and eight asyncio tasks run the last two.

Write the answer before you run anything, then compare. It is the questions-first habit from our code comprehension round post, applied to one bug class.

A quick way to check your unassisted reading on other code is the free Unrust diagnostic, linked at the end of this post.

# shapes.py, excerpt: the five shapes that can go wrong (the fixes come later)
import asyncio
import functools
import threading
import time


# ---- Shape 1: a plain global counter -------------------------------------------------------------
counter = 0


def bump_plain(n):
    global counter
    for _ in range(n):
        counter += 1


# ---- Shape 2: the same line, but the value lives behind a property --------------------------------
class Stats:
    def __init__(self):
        self._hits = 0

    @property
    def hits(self):
        return self._hits

    @hits.setter
    def hits(self, value):
        self._hits = value


def bump_property(stats, n):
    for _ in range(n):
        stats.hits += 1


# ---- Shape 3: check, then act (threads) ----------------------------------------------------------
cache = {}
computed = []  # list.append is documented as atomic, so this log itself is safe


def slow_square(key):
    computed.append(key)
    time.sleep(0.01)  # stands in for a database or network call
    return key * key


def get_square(key):
    if key not in cache:
        cache[key] = slow_square(key)
    return cache[key]


# ---- Shape 4: check, then act (asyncio) ----------------------------------------------------------
sessions = {}
created = []


async def open_session(user):
    created.append(user)
    await asyncio.sleep(0.01)  # stands in for a network call
    return "session-for-" + user


async def get_session(user):
    if user not in sessions:
        sessions[user] = await open_session(user)
    return sessions[user]


# ---- Shape 5: read, await, write (asyncio) -------------------------------------------------------
balance = 0


async def deposit(amount):
    global balance
    current = balance
    await asyncio.sleep(0)  # any await is a point where another task can run
    balance = current + amount

What we ran

Each shape ran on CPython 3.9.25, 3.10.21, 3.11.2, 3.12.16, 3.13.15, 3.14.7 and 3.15.2 with the GIL, plus the free-threaded 3.14.7 build twice: GIL off (the default) and PYTHON_GIL=1 to force it on. Threads wait on a Barrier so they start together, and each cell is 20 runs.

For the counters we report lost updates: 1,000,000 minus what the counter shows. The driver below is a shorter version of our harness; save it next to shapes.py and run it on any build.

We re-ran it on all nine builds before publishing. One run of five printed [500000, 665658, 520758, 498551, 197110] on 3.9.25 and five zeros on each of 3.10.21 to 3.15.2.

# try_plain.py (our short driver; save it next to shapes.py)
import sys
import threading

import shapes


def run_once(threads=4, per_thread=250000):
    shapes.counter = 0
    barrier = threading.Barrier(threads)

    def worker():
        barrier.wait()
        shapes.bump_plain(per_thread)

    pool = [threading.Thread(target=worker) for _ in range(threads)]
    for t in pool:
        t.start()
    for t in pool:
        t.join()
    return threads * per_thread - shapes.counter


if __name__ == "__main__":
    lost = [run_once() for _ in range(5)]
    print(sys.version.split()[0], "lost updates per run:", lost)

What does the result table show?

The bare counter lost updates on 3.9.25 (18 of 20 runs) and on the free-threaded 3.14.7 build (20 of 20), and never on 3.10.21 to 3.15.2 or on the free-threaded binary with the GIL forced on (0 of 20 each). The other four shapes went wrong in 20 of 20 runs on all nine builds.

On 3.9.25 the median loss was 445,134 of 1,000,000 updates; on free-threaded 3.14.7 it was 623,332. The property version lost between 104,709 and 803,826 updates per run.

A loop that never failed in 20 runs is not a proof. The three zero rows for the bare counter still sit on a line the docs call not atomic.

Build                               counter += 1  stats.hits += 1  check, then act  asyncio check  asyncio read-await-write
----------------------------------  ------------  ---------------  ---------------  -------------  ------------------------
3.9.25                              18/20         20/20            20/20            20/20          20/20
3.10.21                             0/20          20/20            20/20            20/20          20/20
3.11.2                              0/20          20/20            20/20            20/20          20/20
3.12.16                             0/20          20/20            20/20            20/20          20/20
3.13.15                             0/20          20/20            20/20            20/20          20/20
3.14.7                              0/20          20/20            20/20            20/20          20/20
3.15.2                              0/20          20/20            20/20            20/20          20/20
3.14.7 free-threaded                20/20         20/20            20/20            20/20          20/20
3.14.7 free-threaded, PYTHON_GIL=1  0/20          20/20            20/20            20/20          20/20

Why can't you reproduce counter += 1 losses on Python 3.10 and later?

Because from 3.10 the interpreter only offers a thread switch at jumps, calls and frame starts, and counter += 1 on a global contains none of them. On 3.9.25 it checks after every instruction. This is an implementation detail of these builds, not a promise.

A CPython commit dated 2021-03-24 made the change. Its message reads "Only check evalbreaker after calls and on backwards egdes" (the spelling is the commit's own) and cites GH-18334.

The block shows the 3.9.25 and 3.10.21 C code, then the bytecode of the loop on 3.9.25 and 3.14.7. Between the load of counter and the store back there is no call, no jump and no function entry.

We read the sources of 3.9.25, 3.10.21, 3.12.16 and 3.14.7. For 3.11.2, 3.13.15 and 3.15.2 we have measurements, not source reading.

# CPython v3.9.25, Python/ceval.c, lines 1041-1047
#define DISPATCH() \
    { \
        if (!_Py_atomic_load_relaxed(eval_breaker)) { \
            FAST_DISPATCH(); \
        } \
        continue; \
    }

# CPython v3.10.21, Python/ceval.c, lines 1315-1318 (used only by some instructions)
#define CHECK_EVAL_BREAKER() \
    if (_Py_atomic_load_relaxed(eval_breaker)) { \
        continue; \
    }

=== CPython 3.9.25 | bump_plain: the loop body is the part between FOR_ITER and the jump back
 19           0 LOAD_GLOBAL              0 (range)
              2 LOAD_FAST                0 (n)
              4 CALL_FUNCTION            1
              6 GET_ITER
        >>    8 FOR_ITER                12 (to 22)
             10 STORE_FAST               1 (_)

 20          12 LOAD_GLOBAL              1 (counter)
             14 LOAD_CONST               1 (1)
             16 INPLACE_ADD
             18 STORE_GLOBAL             1 (counter)
             20 JUMP_ABSOLUTE            8
        >>   22 LOAD_CONST               0 (None)
             24 RETURN_VALUE

=== CPython 3.14.7 | bump_plain: the loop body is the part between FOR_ITER and the jump back
 17           RESUME                   0

 19           LOAD_GLOBAL              1 (range + NULL)
              LOAD_FAST_BORROW         0 (n)
              CALL                     1
              GET_ITER
      L1:     FOR_ITER                16 (to L2)
              STORE_FAST               1 (_)

 20           LOAD_GLOBAL              2 (counter)
              LOAD_SMALL_INT           1
              BINARY_OP               13 (+=)
              STORE_GLOBAL             1 (counter)
              JUMP_BACKWARD           18 (to L1)

 19   L2:     END_FOR
              POP_ITER
              LOAD_CONST               1 (None)
              RETURN_VALUE

Why does the same line fail on every build behind a property?

Because the property getter and setter are Python functions, so a function entry sits between the read and the write, and another thread can run there. stats.hits += 1 lost updates in 20 of 20 runs on all nine builds, including the seven where the bare counter never failed.

Only the storage changed; the line is the same one. A green run on 3.12 therefore says little about a refactor that moves a counter behind a property.

Lost updates per run ranged from 104,709 to 803,826 in our runs, with medians from 377,536 on 3.14.7 to 673,842 on free-threaded 3.14.7.

Why did the cache run the slow call 8 times?

get_square checks whether the key is in the cache, then calls slow_square and stores the result. Eight threads released together all passed the check before any of them stored, so the slow call ran 8 times on every build in 20 of 20 runs; with one Lock around the check and the store it ran once.

functools.lru_cache is not the fix. The docs say the cache is threadsafe, and also "It is possible for the wrapped function to be called more than once if another thread makes an additional call before the initial call has been completed"; our run agrees with 8 calls again.

The dict is not what breaks. The gap between the check and the store is.

Function (8 threads, one key)  Times slow_square ran  Right answer
-----------------------------  ---------------------  ------------
get_square                     8                      1
get_square_locked              1                      1
square_cached (lru_cache)      8                      1

Can asyncio code have race conditions?

Yes. Asyncio tasks share one thread, but every await is a point where another task can run, so a read before an await and a write after it can overwrite each other. In our runs, 8 tasks opened 8 sessions instead of 1, and 8 deposits of 10 left a balance of 10 instead of 80.

Both results were the same on all nine builds in 20 of 20 runs. The fixes are an asyncio.Lock around the check and the open, and no await between the read and the write.

The docs describe asyncio.Lock as "Implements a mutex lock for asyncio tasks. Not thread-safe." Do not share one between threads.

Function (8 tasks)          Result             Right answer
--------------------------  -----------------  ------------
get_session                 8 sessions opened  1
get_session_locked          1 session opened   1
deposit (8 deposits of 10)  balance 10         80
deposit_fixed               balance 80         80

How do you find the gap by reading?

For every shared name, find the read and the write, then ask what can run between them: a call, a property, an await, a sleep or I/O, or on a free-threaded build anything at all. If the honest answer is nothing on your build today, treat that as luck, not as a rule.

Write one line per name before you run the code, as in the read-first exercise above. It is the same reading habit our how to understand a codebase tour uses to find where state changes.

What sits between the read and the write  Example in this post          Can another thread or task run there?
----------------------------------------  ----------------------------  ------------------------------------------------------------
A function call or a property             stats.hits += 1               Yes, on all 9 builds in our runs
An await                                  current = balance; await ...  Yes: another task can run
A sleep or an I/O call                    slow_square                   Yes, on all 9 builds in our runs
Only arithmetic on a global               counter += 1                  Depends on the build: yes on 3.9.25 and free-threaded 3.14.7

How do you make a race show up on purpose?

Put a call, a sleep or an await inside the gap, and run your tests on a free-threaded build. Lowering sys.setswitchinterval to 1e-6 seconds did not help the bare counter on 3.10 to 3.15 in our runs: it stayed at 0 of 10, while 3.9.25 and free-threaded 3.14.7 lost updates in 10 of 10.

The same free-threaded binary with PYTHON_GIL=1 lost 0 of 20 runs, so the loss comes from the build, not from the code alone.

Once a race shows up, reduce it to the smallest case, change one thing and rerun, the loop we describe in our debugging interview post.

Build, switch interval 1e-6 s, 10 runs  counter += 1  stats.hits += 1
--------------------------------------  ------------  ---------------
3.9.25                                  10/10         10/10
3.10.21 to 3.15.2 (six builds)          0/10          10/10
3.14.7 free-threaded                    10/10         10/10
3.14.7 free-threaded, PYTHON_GIL=1      0/10          10/10

Do you still need locks on free-threaded Python?

Yes. The free-threading HOWTO says built-in types like dict, list and set use internal locks, and it recommends threading.Lock or other synchronization primitives instead of relying on them. In our runs, counter += 1 on free-threaded 3.14.7 lost updates in 20 of 20 runs (median 623,332 of 1,000,000).

Our free-threaded results are for 3.14.7 only; we did not run 3.13 or 3.15 free-threaded builds.

How do you prevent a race condition in Python?

Do not share the name if you can. Otherwise hold one threading.Lock across the whole read-modify-write or check-then-act, or in asyncio keep every await out of the gap. Every locked variant lost 0 updates in every run on all nine builds.

The excerpt shows each fix as we ran it. Count privately and merge once is the cheapest, and the next section gives the timings.

# shapes.py, excerpt: the fixes
# ---- Fixes for shapes 1-3 (one threading.Lock) ---------------------------------------------------
lock = threading.Lock()


def bump_plain_locked(n):
    global counter
    for _ in range(n):
        with lock:
            counter += 1


def bump_property_locked(stats, n):
    for _ in range(n):
        with lock:
            stats.hits += 1


def get_square_locked(key):
    with lock:
        if key not in cache:
            cache[key] = slow_square(key)
        return cache[key]


# ---- Not a fix for shape 3: functools.lru_cache --------------------------------------------------
@functools.lru_cache(maxsize=None)
def square_cached(key):
    return slow_square(key)


# ---- Fix for shape 1 without a lock per increment: count privately, merge once -------------------
def bump_partial(n):
    global counter
    mine = 0
    for _ in range(n):
        mine += 1
    with lock:
        counter += mine


async def get_session_locked(user, session_lock):
    async with session_lock:
        if user not in sessions:
            sessions[user] = await open_session(user)
        return sessions[user]


async def deposit_fixed(amount):
    global balance
    await asyncio.sleep(0)  # do the awaiting first, then read and write with no await in between
    balance += amount

What the fixes cost on our machine

Per-thread partial sums took 0.015 to 0.080 s per million increments. A lock per increment took 0.128 to 0.359 s on 3.10 to 3.15 and the free-threaded builds, and 4.057 s on 3.9.25.

A lock held across the two property calls took 4.660 to 5.418 s per run on 3.9.25 to 3.12.16, and 0.199 to 0.374 s on 3.13.15 and later. We measured this and did not investigate the cause, so read it as a measurement, not an explanation.

Build, median s per 1,000,000 increments  plain  plain_locked  partial  property  property_locked
----------------------------------------  -----  ------------  -------  --------  ---------------
3.9.25                                    0.089  4.057         0.068    0.331     5.418
3.10.21                                   0.100  0.332         0.080    0.379     5.386
3.11.2                                    0.069  0.322         0.029    0.208     4.759
3.12.16                                   0.078  0.359         0.065    0.208     4.660
3.13.15                                   0.063  0.315         0.049    0.174     0.344
3.14.7                                    0.070  0.258         0.041    0.182     0.374
3.15.2                                    0.073  0.147         0.038    0.171     0.260
3.14.7 free-threaded                      0.036  0.128         0.015    0.106     0.200
3.14.7 free-threaded, PYTHON_GIL=1        0.038  0.131         0.047    0.099     0.199

Which fix fits which shape

Start from the shape, not from the tool. A counter wants a lock or private partial sums, a check-then-act wants one lock around both steps, and an asyncio read-await-write wants the await moved out of the gap.

The table lists what each fix did in our runs. A lock fixes every shape here, and the cheapest fix is the one that avoids sharing.

None of this tells you that your own code is free of races. It tells you which question to ask of each shared name.

Shape                        Fix                                         Result in our runs
---------------------------  ------------------------------------------  -------------------------------------------
Bare or property counter     Per-thread partial sums, or one Lock        0 lost updates in every run on all 9 builds
Check, then act, threads     One Lock around the check and the store     Slow call ran 1 time (8 without)
Check, then act, asyncio     asyncio.Lock around the check and the open  1 session opened (8 without)
Read, await, write, asyncio  No await between the read and the write     Balance 80 (10 without)
Check, then act, threads     functools.lru_cache                         Not a fix: slow call ran 8 times

Where do these races show up outside a test loop?

As symptoms such as a total that is too low, a duplicate record, or a slow call that ran more than once. We did not measure real applications, so this is a reading aid, not a statistic. Our use case on investigating a production bug covers the steps once a symptom like that reaches you.

When you review a change that moves state into a property or adds an await, ask the gap question. Our code review interview post practices judging a diff in that way.

What we did not verify

Other machines and operating systems, PyPy, free-threaded 3.13 and 3.15, multiprocessing, and real applications. We also did not investigate why the contended lock was slower on 3.9 to 3.12.

Every number is from one machine, and a passing loop is not a proof that code is safe.

FAQ: Python race conditions

Is counter += 1 thread-safe in Python? No. The docs FAQ lists i = i + 1 as not atomic, and in our runs a bare counter += 1 lost updates on 3.9.25 and free-threaded 3.14.7 but not on 3.10 to 3.15, which is an implementation detail of those builds. Use a Lock or per-thread partial sums instead of testing.

Why can't I reproduce my race condition on Python 3.10, 3.11 or 3.12? In the 3.10.21 and 3.12.16 sources the interpreter checks for a thread switch at jumps, calls and frame starts, so a bare counter += 1 was never interrupted in our runs. Put a call, a property or an await in the gap and the race returns.

How do you prevent a race condition in Python? Avoid sharing the name, or hold one threading.Lock across the whole read-modify-write or check-then-act. In asyncio, keep every await out of the gap or use asyncio.Lock. Every locked variant in our runs lost 0 updates, and per-thread partial sums were the cheapest fix we timed.

Do I still need locks on free-threaded Python? Yes. The docs recommend threading.Lock or other synchronization primitives instead of relying on the internal locks of built-in types, and a bare counter += 1 lost updates in 20 of 20 runs on free-threaded 3.14.7 in our measurements. Those results are for 3.14.7 only.

Can asyncio code have race conditions? Yes. Every await lets another task run, so a read before an await and a write after it can overwrite each other. In our runs 8 tasks opened 8 sessions instead of 1, and 8 deposits of 10 left a balance of 10, not 80.

References and next steps

See what you can do with the AI off

Take Unrust's free diagnostic with AI and autocomplete off: a warm-up and 3 drills in about 14 minutes, with no account needed. It measures unassisted skill, and it does not predict an interview or on-call result.

More from the blog