Why Python’s Free-Threaded Build Breaks Multithreaded Code That Relied on the GIL

The underside of a computer CPU showing its pin grid, representing the processor hardware that runs Python threads

Python’s free-threaded build (officially supported starting with 3.13, stabilizing further in 3.14) removes the Global Interpreter Lock, and that breaks a category of multithreaded code that happened to work only because the GIL was serializing access to shared state. AI coding assistants trained mostly on GIL-era Python don’t know this distinction exists, so they keep generating patterns — unlocked check-then-act on a shared dict, raw iterator sharing across threads — that were never actually safe, just invisible until now.

This is a breakdown of exactly what changes under free threading, sourced from Python’s own how-to guide, with the specific code patterns that silently stop being safe.

What the GIL was quietly protecting

Under the normal (non-free-threaded) interpreter, only one thread executes Python bytecode at a time. That had a side effect developers leaned on without naming it: any sequence of bytecode instructions that fit between two thread switches behaved as if it were atomic. A lot of code written to be “thread-safe” is really just code that was never tested under true parallelism, because the GIL made races between threads rare enough not to show up.

Free-threaded CPython removes that accidental protection. Python’s own documentation is direct about what’s left: built-in types like dict, list, and set use internal locks that “behave similarly to the GIL,” but the docs explicitly add that “Python has not historically guaranteed specific behavior for concurrent modifications to these built-in types, so this should be treated as a description of the current implementation, not a guarantee of current or future behavior.” In other words: individual operations on a dict won’t corrupt the dict, but that says nothing about a sequence of operations.

The GIL’s removal wasn’t an incidental side effect of other CPython changes â it was proposed specifically to fix this limitation. The CPython steering council’s own accepted proposal, PEP 703, states its motivation plainly: “The GIL is an obstacle to using multi-core CPUs from Python efficiently.” That’s the tradeoff this whole piece is about: removing the obstacle to parallelism also removes the accidental atomicity guarantees that a lot of existing code, including AI-generated code, was quietly depending on.

The pattern AI assistants keep generating: check-then-act

The most common break is the check-then-act pattern on a shared container — incrementing a counter, deduplicating a key, or lazily initializing a cache entry:

counts[key] = counts.get(key, 0) + 1

Each half of that line — the read and the write — is internally safe on its own. But the two halves together are not atomic, and under genuine parallel execution two threads can both read the same old value before either writes, silently dropping an increment. Ask an AI coding assistant to “cache the result of this expensive function across threads” or “deduplicate items from multiple worker threads,” and it will very often produce exactly this shape, because it’s the idiomatic single-threaded pattern and nothing in the prompt signals that free threading is in play. The fix isn’t exotic — wrap the check-then-act in a threading.Lock — but the assistant won’t add it unless you ask, because the code “looks correct” by every convention it learned from GIL-era training data.

The pattern that crashes instead of corrupting: shared iterators

A second pattern is more dangerous because it doesn’t just produce wrong numbers — it can crash the interpreter. Python’s free-threading documentation states plainly: “Sharing the same iterator object between multiple threads is generally not safe and threads may see duplicate or missing elements when iterating or crash the interpreter.” A common AI-generated worker-pool pattern — creating one generator or iterator and handing it to several worker threads to pull from — falls directly into this. The safe rewrite is to give each thread its own iterator slice, or to pull items through a thread-safe queue instead of a shared generator.

C extensions: the GIL comes back without telling you

If your project depends on a C extension that hasn’t been explicitly built or marked for free threading, you may not even be running free-threaded code even though you think you are. The documentation says: “The GIL may also automatically be enabled when importing a C-API extension module that is not explicitly marked as supporting free threading. A warning will be printed in this case.” That warning is easy to miss in a noisy CI log, and the practical effect is that your “free-threaded” workload quietly falls back to GIL behavior the moment it imports one unmarked dependency — numpy, lxml, or an internal compiled module, for example — which can mask the exact bugs described above during testing and then expose them later once every dependency catches up.

Frame inspection breaks differently too

Debugging and profiling code that walks other threads’ stack frames is a smaller but real failure category. The docs warn: “It is not safe to access frame objects from other threads and doing so may cause your program to crash. This means that sys._current_frames() is generally not safe to use in a free-threaded build.” If your test suite or an AI-generated debugging helper calls sys._current_frames() to inspect what other threads are doing — a common pattern in deadlock detectors and custom profilers — that code needs rewriting, not just locking. inspect.currentframe() and sys._getframe() stay safe, but only “as long as the resulting frame object is not passed to another thread.”

How to actually tell what you’re running

Three checks answer three different questions, and mixing them up is its own source of confusion:

  • Does this Python build support free threading at all? Run python -VV or check sys.version for the string “experimental free-threading build.”
  • Was this build compiled with free threading enabled? Check sysconfig.get_config_var("Py_GIL_DISABLED") — the docs call this “the recommended mechanism for decisions related to the build configuration.” A return value of 1 means the build supports it.
  • Is the GIL actually off right now, in this process? Call sys._is_gil_enabled(). A build that supports free threading can still be running with the GIL re-enabled — either because you set the PYTHON_GIL=1 environment variable or the -X gil flag, or because an unmarked C extension silently re-enabled it on import.

A CI pipeline that only checks the first of these and assumes the other two follow will pass tests that never actually exercised free-threaded behavior.

Immortal objects: a memory surprise that isn’t a leak

One more free-threading behavior change is worth knowing before you go looking for a memory leak that isn’t one. Some objects become “immortal” under the free-threaded build, meaning they’re never deallocated and their reference counts stop being modified. The documentation lists what gets immortalized: module-level functions, method descriptors, code objects, modules and their dictionaries, classes, numeric and string literals, and strings returned by sys.intern(). The docs warn that “applications that create many objects of these types may see increased memory usage” — if you dynamically generate a large number of small functions, classes, or interned strings at runtime, expect memory growth that a profiler will correctly report but that isn’t a bug in your code. Python’s documentation notes this is “expected to be addressed in the 3.14 release,” so treat it as a known, temporary characteristic of the current implementation rather than something to engineer around permanently.

What to actually ask an AI assistant to change

Rather than trusting a general “review this for thread safety” prompt, it’s more reliable to ask for the three specific patterns above by name: unprotected check-then-act sequences on shared containers, iterators or generators shared across threads, and calls to sys._current_frames(). Our broader framework for structuring this kind of request is in AI code review prompts for security, correctness, edge cases, and test gaps — the “edge cases” pass is the one to point explicitly at concurrency assumptions, since a general correctness pass tends to accept code that is syntactically fine and only wrong under parallel execution.

This is also a case of a broader issue we’ve covered before: AI assistants default to the conventions baked into their training data, which for Python concurrency means GIL-era idioms. Our piece on why AI coding assistants keep suggesting deprecated APIs covers the same root cause applied to library APIs rather than concurrency assumptions — the fix pattern (naming the exact thing that changed, rather than asking generally for “modern” or “safe” code) is the same in both cases.

If you’re adding tests specifically to catch these races, write them to run the suspect function from several threads concurrently with a tight loop and an assertion on the final shared count — a single-threaded unit test will pass every time regardless of whether the locking is correct, because the race only shows up under genuine concurrent execution. Our guide on writing unit tests with edge cases first applies directly here: “runs under 8 concurrent threads without losing an update” is the edge case to write down before asking an assistant to generate the test, not after. And since a lot of these bugs look identical to the catastrophic backtracking failures covered in our pre-merge checklist for AI-generated regex — code that passes review and then fails only under a specific runtime condition nobody tested for — the same discipline of naming the exact runtime condition in the review prompt applies to both.

One more number worth knowing before you adopt this build in production: Python’s own documentation reports free threading currently carries roughly 40% overhead on the pyperformance benchmark suite in 3.13, mainly because the specializing adaptive interpreter is disabled in the free-threaded build. That’s expected to narrow in later releases, but it means the migration isn’t free even once the thread-safety bugs are fixed — budget for a performance regression, not just a correctness pass.

Photo: Justin Mathews, CC BY 3.0, via Wikimedia Commons. Source: Python’s official free-threading how-to guide.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top