A global interpreter lock (GIL) is a synchronization mechanism that permits only one thread at a time to execute within a protected interpreter runtime. It is most closely associated with CPython, the reference implementation of Python, although similar mechanisms exist in other language implementations. In conventional GIL-enabled CPython, a thread normally must hold the lock to execute Python code or manipulate Python objects through the runtime’s C interface.
The GIL simplifies the protection of shared interpreter state, including object bookkeeping and memory management. Its principal cost is that multiple threads cannot simultaneously execute ordinary Python code within the same GIL-protected interpreter, even on a computer with several processor cores. This restriction does not prevent all concurrency or all parallelism: threads may overlap input/output operations, native libraries may execute outside the lock, and separate processes or suitably isolated interpreters may run independently.
The meaning and consequences of the GIL depend on the implementation and version. Python does not require a GIL as a language feature. CPython 3.12 introduced support for interpreters with separate GILs, and CPython 3.13 introduced an experimental free-threaded build that can run with the GIL disabled. Understanding the mechanism therefore requires distinguishing language semantics, runtime implementation, native-extension behavior, and application-level synchronization.
Scope and architectural purpose
An interpreter maintains more than the instructions currently being executed. Its runtime may manage object allocation, reference counts, module registries, exception state, caches, and the execution state of many threads. When threads share these facilities, simultaneous updates can corrupt data unless the implementation coordinates access. A global interpreter lock addresses much of this problem by placing a broad mutual-exclusion boundary around runtime execution.
The lock is “global” relative to its protection domain, not necessarily to an entire machine or even an entire process. In older CPython designs, interpreters within one process shared the same GIL. With per-interpreter GIL support, different interpreters can have different locks. Separate processes normally have separate interpreter runtimes and therefore separate GILs. A machine running eight Python processes may consequently have eight threads executing Python code at once, even if every process uses a GIL-enabled build.
Conceptually, the GIL implements mutual exclusion, commonly using lower-level facilities such as a mutex and a condition variable. It is not a processor restriction and does not disable cores. The operating system can schedule many application threads simultaneously; the interpreter lock determines which of those threads may enter the protected runtime. A thread waiting for the GIL may be runnable from the operating system’s perspective while unable to make progress in Python execution.
A broad lock reduces the number of independently synchronized operations that the runtime must perform. Instead of protecting every object-field update with its own lock or atomic operation, an implementation can rely on the fact that only one participating thread is manipulating protected state. This can simplify both interpreter development and the interface presented to native extensions. The cost is a deliberately coarse boundary: operations on entirely unrelated Python objects may still compete for the same lock.
The GIL should also be distinguished from an application lock. An application mutex might protect a bank-account balance or a queue invariant; the GIL primarily protects the interpreter’s ability to operate safely. It does not know which combinations of application operations must occur indivisibly. Likewise, it is not a security sandbox or a boundary between mutually untrusted threads. Threads in one process generally share an address space and substantial runtime state. The interpreter lock regulates execution within that shared environment rather than isolating its participants.
Object management and the CPython execution model
CPython normally compiles Python source into bytecode, which its evaluation machinery executes. The GIL traditionally surrounds this execution machinery and many operations invoked from it. An executing thread also has an associated thread state containing information needed by the interpreter, such as the current exception context and execution-related bookkeeping. Possession of a valid thread state and possession of the GIL are related requirements in a GIL-enabled runtime, but they are not identical concepts.
A central reason for CPython’s historical design is reference counting. Most Python objects track how many strong references point to them. Creating another owning reference increments this count; releasing an owning reference decrements it. When the count reaches zero, object destruction can occur immediately. Without synchronization, two processors updating the same ordinary counter can lose an increment or decrement. An incorrect count can cause premature destruction, memory corruption, or memory that is never reclaimed.
For example, suppose two threads independently acquire references to one object. If both read the same old count and both write back that count plus one, the final value records only one additional reference rather than two. The GIL traditionally prevents this particular interleaving by serializing the relevant runtime operations. It also protects many container internals and other implementation details whose correctness historically depended on that serialization.
Reference counting is not CPython’s only memory-management mechanism. Its cyclic garbage collector detects groups of objects that refer to one another but are unreachable from the rest of the program. A list containing itself illustrates why reference counting alone is insufficient: its internal reference prevents its count from reaching zero. Runtime synchronization must therefore accommodate both routine reference updates and collector activity, including interactions with finalization and weak references.
Object destruction also complicates simple descriptions of the lock. Releasing a reference may trigger a finalizer, and that finalizer may execute Python code. A seemingly local native operation can therefore re-enter the interpreter and run arbitrary application behavior. Similar re-entry can occur through callbacks, descriptors, or user-defined equality methods. This is one reason that statements such as “the GIL makes every C operation atomic” are inaccurate.
The GIL does not ordinarily protect arbitrary memory belonging to unrelated native libraries. If an extension releases it and then updates a shared native buffer, that extension must supply whatever synchronization its buffer requires. Conversely, native code that holds the GIL can still violate memory safety through an invalid pointer or incorrect ownership bookkeeping. The lock provides an important runtime invariant, not a general proof that all code in the process is safe.
Scheduling, handoff, and blocking operations
A GIL-enabled interpreter must periodically give other threads an opportunity to execute. Otherwise, one CPU-intensive thread could retain the lock indefinitely. CPython’s switching mechanism has changed over time. Older versions used an instruction-count-oriented check interval, whereas the redesigned GIL introduced in Python 3.2 used a time-oriented handoff mechanism. These mechanisms should not be understood as exact quotas of Python statements or processor instructions.
In modern CPython, sys.setswitchinterval() controls the interpreter’s thread-switch interval, expressed in seconds. A typical default is 0.005 seconds, or five milliseconds. The interval influences when competing threads request a handoff, but it is not a real-time scheduling guarantee. The interpreter must reach a suitable point to respond, and the operating system determines when a waiting thread actually runs. A long native operation that continues holding the GIL can substantially delay another thread.
Internally, contention involves a current lock holder, threads waiting for acquisition, and coordination that requests the holder to relinquish execution. CPython uses synchronization machinery rather than relying solely on continuously spinning until the lock becomes available. The precise implementation is version-dependent. Fairness is also not equivalent to strict round-robin scheduling: a thread becoming eligible to acquire the lock does not establish an exact ordering among every competing thread.
Blocking input/output is a major exception to continuous GIL ownership. Before waiting for a socket operation or another supported blocking call, CPython commonly releases the GIL. Another thread can then run Python code while the first thread waits for an external event. When the operation finishes, the first thread must reacquire the lock before returning to protected interpreter activity. Thus a network client can overlap several requests even though response-processing code is serialized.
Lock handoff has performance costs. A thread may be descheduled, another awakened, and processor-local state displaced. Repeated transfers can interact with CPU caches and CPU scheduling, particularly when threads run on different cores. Short computations interspersed with frequent lock transfers can therefore perform worse than the same work executed sequentially. An input/output-oriented thread may also experience latency while waiting for a CPU-intensive thread to relinquish the interpreter.
The switch interval is not a correctness mechanism for application code. Increasing it does not make a compound operation reliably indivisible, and decreasing it does not guarantee fairness or responsiveness. Signals, callbacks, native calls, operating-system delays, and interpreter-version changes all affect execution. Applications requiring bounded scheduling behavior cannot infer such bounds merely from the GIL’s nominal switching interval.
Workload behavior and limits on scaling
The GIL’s performance effect depends on where a workload spends its time. A CPU-bound loop that repeatedly performs ordinary Python arithmetic, dictionary lookups, or object manipulation generally occupies the protected interpreter. Dividing that loop among several threads in one GIL-enabled interpreter does not let those threads execute its Python operations simultaneously. Additional threads may add synchronization and scheduling overhead without providing corresponding computational throughput.
An input/output-bound workload has a different execution profile. Threads waiting for network responses, file operations, or other supported blocking services can release the GIL, allowing useful work elsewhere. For instance, several download threads may overlap the remote servers’ response times. The speedup depends on how much time is actually spent waiting, whether the relevant operations release the lock, and whether local processing becomes the new bottleneck.
Native numerical computation creates another important case. NumPy and other computational libraries can perform substantial work in native code while releasing the GIL. One Python thread may start an array operation that runs outside the interpreter, while another thread starts a separate operation. A native library may also create its own worker threads. The resulting parallelism belongs to the native computation rather than to simultaneous execution of ordinary Python bytecode under one GIL.
This distinction is relevant to systems using PyTorch, TensorFlow, or a graphics processing unit. Python may coordinate a computation while most arithmetic occurs in native kernels or on an accelerator. Removing the GIL does not automatically accelerate those kernels. Conversely, Python-side preparation, callbacks, or result processing can still become a serialized bottleneck even when the numerical phase is highly parallel.
Amdahl’s law expresses the general limitation imposed by a serial fraction. Under an idealized model, if fraction of execution remains serial and the rest scales perfectly across workers, the maximum speedup is
If 80 percent of a workload remains effectively serialized, unlimited parallel resources cannot produce more than a fivefold speedup under this model. Actual performance also includes communication, memory-bandwidth constraints, lock contention, and load imbalance.
Meaningful measurement therefore separates wall-clock latency, total throughput, CPU utilization, and memory consumption. High utilization across several cores does not prove that Python code is running in parallel: native worker pools may account for it. Equally, a low speedup does not establish that the GIL is the sole cause. Allocation overhead, shared data, insufficient task size, and competition among nested thread pools can dominate even in a runtime without a GIL.
Application correctness and synchronization
The GIL prevents some forms of simultaneous interpreter-state corruption, but it does not eliminate race conditions in Python applications. A race can arise whenever correctness depends on the ordering of operations performed by different threads. Such a problem does not require the threads to execute at precisely the same instant; an unfavorable interleaving is sufficient.
A common example is a check followed by an action. A thread may test whether a shared collection contains an item and then insert a replacement if it does not. Another thread can intervene between these steps and make the earlier observation obsolete. Similarly, updating two related fields separately can expose an inconsistent intermediate state. Even if each individual container operation is protected internally, the relationship between them remains an application-level responsibility.
The expression counter += 1 is also not a portable synchronization primitive. Its evaluation involves reading a value, performing an operation, and assigning a result, and user-defined objects can execute additional code during these steps. Whether a particular example exhibits a lost update in a particular CPython release depends on execution details. The absence of a failure in repeated tests does not establish a language guarantee.
Applications use explicit locks to establish critical sections around invariants. Other coordination mechanisms include condition variables, events, semaphores, and synchronized queues. A queue can combine storage with a defined protocol for blocking producers and consumers; a bare list does not automatically provide that protocol. Explicit synchronization also documents which state is shared and which sequences must remain indivisible.
Multiple locks introduce ordering problems. A deadlock can occur if one thread holds an application lock while waiting for an action that requires another thread to acquire that same lock. The GIL does not prevent this. Native extensions can create additional cycles involving an application mutex, an internal library lock, and GIL acquisition. A callback into Python while holding a native lock is particularly sensitive because arbitrary callback code may attempt further locking.
The distinction between runtime safety and application correctness becomes more visible in free-threaded execution. Internal container locks can keep a dictionary structurally valid while an application still makes an incorrect decision based on stale contents. Conversely, code with explicit, correctly scoped synchronization need not depend on incidental GIL behavior. Neither GIL-enabled nor free-threaded Python should be treated as supplying a universal transactional model or a complete memory model for arbitrary unsynchronized native accesses.
Native extensions and embedding interfaces
The GIL has long been part of the practical contract of CPython’s native-extension API. Extensions written in C or related languages typically manipulate objects through functions that assume the calling thread has the required interpreter state and, in a GIL-enabled build, holds the GIL. Violating those assumptions can corrupt reference counts or access runtime structures concurrently.
The macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS delimit a common pattern for temporarily leaving protected execution. In a conventional build, the enclosed region releases the GIL and later reacquires it. That region can perform blocking input/output or a substantial native computation, but it must not freely call Python’s object APIs. The extension must also ensure that any native memory it touches remains valid and appropriately synchronized throughout the operation.
Releasing the lock is useful only when the native task is sufficiently independent. An algorithm that calls a Python callback for every processed element may repeatedly re-enter the interpreter and surrender much of the potential parallel benefit. By contrast, a long numerical kernel operating on stable native buffers can amortize transition costs. The presence of native code alone therefore says little about whether an extension permits parallel execution.
Threads created by an external library pose a related problem. Such a thread may call back into an embedded Python runtime without already having Python thread state. APIs including PyGILState_Ensure() and PyGILState_Release() support common attachment and locking patterns. Their convenience does not make them universal solutions for every embedding design: their assumptions require particular care when multiple interpreters are involved, because callbacks must be associated with the intended interpreter.
Extension compatibility also depends on the ownership of global state. A native module may store cached Python objects or mutable settings in process-global C variables. Those variables can undermine interpreter isolation even when separate interpreters have separate GILs. CPython’s module initialization facilities and per-module state mechanisms support better isolation, but existing extension code may need substantial restructuring to use them correctly.
Free-threaded builds introduce another compatibility boundary. Extensions must be built for the appropriate configuration and must accurately declare whether they support execution without the GIL. An extension that has not declared such support can cause the runtime to enable the GIL when it is imported, subject to configuration controls. Correct support entails more than compiling successfully: borrowed references, container access, internal caches, and native global variables may all require revised synchronization or ownership rules.
Historical development and alternative designs
The GIL emerged in CPython’s early multithreading implementation under conditions different from those of modern many-core systems. A coarse interpreter lock offered a practical way to add threads while preserving a straightforward reference-counting implementation and a manageable extension interface. As multicore processors became common, the inability of ordinary CPU-bound Python threads to use several cores simultaneously became a more prominent architectural limitation.
An influential early attempt to remove the lock was Greg Stein’s free-threading work in the 1990s. It replaced broad serialization with more fine-grained protection, but the overhead imposed on common execution paths helped make the approach unattractive for mainstream adoption. The historical issue was not simply whether a GIL-free interpreter could be constructed. It was whether it could preserve acceptable single-thread performance, compatibility, memory use, and maintainability.
Antoine Pitrou’s redesigned GIL, incorporated in Python 3.2 in 2011, addressed scheduling and contention behavior rather than removing serialization. Earlier switching behavior could allow a CPU-bound thread to reacquire the lock repeatedly while another thread struggled to run. The redesign changed the handoff machinery and timing model. It improved an aspect of responsiveness without turning one GIL-protected interpreter into a parallel bytecode engine.
Python implementations have made different choices. Jython runs on the Java virtual machine and does not use CPython’s GIL. IronPython, implemented for the .NET environment, likewise follows a different threading architecture. These implementations demonstrate that Python’s language definition does not require a global interpreter lock, but their extension compatibility and execution characteristics differ from CPython’s. A CPython-specific binary extension cannot simply be assumed to work unchanged on another runtime.
PyPy, another Python implementation, has conventionally retained a GIL despite using a different execution architecture and a tracing just-in-time compiler. Experimental approaches involving transactional execution have also been explored, but they have not displaced its conventional model. Avoiding a GIL is therefore not an automatic consequence of using a different interpreter or compilation technique.
Similar terminology appears outside Python. CRuby, the main implementation of Ruby, uses a Global VM Lock, or GVL, that serializes much Ruby execution while allowing some native or blocking work outside it. The exact protection domain and release behavior differ from CPython’s. Broad interpreter locks represent one point in a larger design space that also includes fine-grained locking, actor-style isolation, immutable shared objects, and message passing between independent execution contexts.
Per-interpreter isolation and free-threaded CPython
CPython’s recent development has pursued two distinct routes to greater parallelism. One isolates work into interpreters that can run independently; the other permits multiple threads to execute within one interpreter without a GIL. These approaches solve different sharing problems. Independent interpreters reduce shared mutable runtime state, whereas free-threaded execution retains a broadly shared object environment and must synchronize it more selectively.
PEP 684, implemented for Python 3.12, introduced support for a per-interpreter GIL. Through the relevant C API configuration, interpreters can be created with their own locks. Threads running in separate such interpreters can execute Python code in parallel. Subinterpreters already existed, but historically shared the process-wide GIL; their mere existence did not previously imply parallel Python execution. Extension modules also need suitable isolation to operate safely in this arrangement.
Separate interpreters do not behave like ordinary threads sharing every Python object. They have distinct interpreter state, and communication must respect object-sharing restrictions. This can make them conceptually closer to separate processes, although they still inhabit one process and share some underlying resources. Process-based parallelism remains another option, using interprocess communication or controlled shared memory, with different startup, serialization, and failure-isolation costs.
PEP 703, authored by Sam Gross and accepted in 2023, specified an optional GIL for CPython. Python 3.13, released in 2024, introduced the experimental free-threaded build. Python 3.14 subsequently moved free-threaded Python to officially supported status under the staged transition described in PEP 779; it remained an optional build rather than making GIL-free execution universal. Version, build configuration, runtime settings, and imported extensions all matter when determining whether a program is actually running without the GIL.
Free-threading replaces one broad protection mechanism with several coordinated techniques. Biased reference counting makes many reference updates cheaper when performed by an object’s owning thread, while shared-reference handling supports access from other threads. Deferred reference counting and immortal objects reduce some reference-update costs. Containers use internal locking and carefully designed access paths, and memory-management changes help make concurrent access safe. Garbage collection still requires coordination and can pause participating threads.
These techniques redistribute rather than abolish synchronization costs. Contended objects, allocator behavior, cache coherence, and shared native-library state can limit scaling. Internal locks generally preserve runtime integrity, not the atomicity of multi-step application algorithms. Existing code may therefore need explicit synchronization even when it previously appeared reliable under a GIL. Extension compatibility, single-thread overhead, memory consumption, and realistic multicore performance remain central criteria for evaluating the different CPython execution configurations.