Programming Search⌘K

Conceptcore

Global interpreter lock

Also called GIL, GVL, global VM lock, Python GIL, free-threaded Python, free threading, --disable-gil.

A global interpreter lock lets only one thread of a process run interpreter code at a time. CPython and Ruby MRI have one, so CPU-bound threads take turns instead of running in parallel.

Applies to
core-languages

Idea

A global interpreter lock, or GIL, is one lock for a whole interpreter. A thread must hold the lock to run interpreter code, so only one thread runs that code at a time. The Python glossary calls the GIL "The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time".1 Wikipedia gives the general form: only one native thread for each process "can execute basic operations", such as memory allocation and reference counting, at a time.2

The lock makes the interpreter simpler. Its own data, such as the reference counts of objects, is "implicitly safe against concurrent access".1 The price is parallelism. The lock is held "at the expense of much of the parallelism afforded by multi-processor machines".1 Threads still help with I/O, but threads that only calculate take turns.3

Some popular interpreters that have a GIL are CPython and Ruby MRI.2 In Ruby, the lock is called the Global VM Lock, or GVL.2

How it works

Taking turns

There is always one GIL for each interpreter process.2 A thread that runs interpreter code holds it. The other threads wait until the holder releases it:

  • At blocking calls. In CPython, "the GIL is always released when doing I/O".1 A thread that waits for a file, a socket or a sleep lets other threads run.
  • In extension code. Some extension modules release the GIL "when doing computationally intensive tasks such as compression or hashing".1 Then their C code can run in parallel with Python code.
  • After a time slice. CPython asks a running thread to give up the lock after a switch interval. sys.setswitchinterval sets "the ideal duration of the “timeslices” allocated to concurrently running Python threads".4 The default is 5 milliseconds.5 The interpreter does not choose the next thread: it "doesn’t have its own scheduler", and the operating system decides.4

What it means for programs

The Python documentation sums it up: "the GIL limits the performance gains of threading when it comes to CPU-bound tasks, as only one thread can execute Python bytecode at a time".3 For CPU-bound work on many cores, it advises "multiprocessing or concurrent.futures.ProcessPoolExecutor". For I/O, "threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously".3

The Python example shows both cases. Four threads that count down take at least twice as long as one thread, because they take turns. Four threads that sleep for 0.2 seconds finish in under 0.4 seconds, because a sleeping thread releases the lock.

Why interpreters use one

Wikipedia gives three reasons for a GIL:2

  • Speed with one thread. The interpreter does not need to take and release a lock for each data structure.
  • C libraries. It is easy to use C libraries that are not thread-safe.
  • Simple code. One lock is much simpler to write than a lock-free interpreter or one with fine-grained locks.

Free-threaded CPython

PEP 703 says that the GIL "is an obstacle to using multi-core CPUs from Python efficiently". It proposed a build option, --disable-gil, to run Python code without the lock.6 CPython 3.13 added this build as an experiment.7 The documentation calls it free threading: a build "where the global interpreter lock (GIL) is disabled".8 The executable of the free-threaded build is "usually called python3.13t".7

In the free-threaded build:

  • Threads can run Python code in parallel on all cores.8
  • sys._is_gil_enabled() tells whether the GIL is on in the running process.7
  • The GIL can come back. Some extension modules "may not be ready for use in a free-threaded build, and will re-enable the GIL".8 The PYTHON_GIL environment variable and the -X gil option also turn it on.8
  • Built-in types such as dict, list and set use internal locks that "behave similarly to the GIL".8
  • Code with one thread runs a little slower. On the pyperformance benchmarks, the average overhead is "from about 1% on macOS aarch64 to 8% on x86-64 Linux systems".8

In languages

LanguageVerdictNote
PythonNative
C++Absent
JavaAbsent
CAbsentC threads are operating system threads that run in parallel. No separate example file. Alternative: The C11 atomic types, like std::atomic in the C++ example.
C#Absent
JavaScriptAbsent
TypeScriptAbsentTypeScript runs on a JavaScript engine, which has no GIL. No example file exists. Alternative: Workers with a SharedArrayBuffer and Atomics, as in the JavaScript example.
GoAbsent
RustAbsent
KotlinAbsentOn the JVM, Kotlin threads run in parallel, as in the Java example; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query has no threads.
BashDoes not applyA Bash script runs in one thread for each process.
PowerShellAbsentPowerShell runs on .NET, which has no GIL; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no threads.
CSSDoes not applyStyle rules have no threads.
Regular expressionsDoes not applyA pattern has no threads.
Language Verdict Mechanism
Python native the GIL in CPython; a free-threaded build without it
JavaScript absent one thread for each engine instance; workers in parallel
TypeScript absent as JavaScript
Java absent JVM threads run in parallel
Kotlin absent JVM threads run in parallel
C# absent .NET threads run in parallel
Go absent goroutines on up to GOMAXPROCS threads
Rust absent operating system threads
C absent operating system threads
C++ absent operating system threads
Bash n/a one thread for each process
PowerShell absent .NET threads; runspaces in parallel
SQL n/a a query has no threads
Regex n/a a pattern has no threads
HTML/CSS n/a markup and style rules have no threads
  • Python. CPython has the GIL. In CPython, "only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation)".3 Other implementations differ: Jython, on the JVM, does "not use global interpreter locks".2 The multiprocessing package runs work in subprocesses, "effectively side-stepping the Global Interpreter Lock".9
  • Ruby. Threads in one ractor share "a Ractor-wide global lock like GIL (GVL in MRI terminology), so they can’t run in parallel".10 Ractors are Ruby's way to run code in parallel: "the Global Virtual Machine Lock (GVL) is held per ractor, so ractors can run in parallel".11 JRuby has no global interpreter lock.2
  • JavaScript. An engine runs the code of one instance on one thread, so it needs no GIL. For parallel work, Node.js has workers. A worker is "an independent JavaScript execution thread", and workers "are useful for performing CPU-intensive JavaScript operations".12 Workers can share a SharedArrayBuffer, and the Atomics object has "static methods for carrying out atomic operations" on it.13
  • Java. Threads may run on "many hardware processors", by "time-slicing a single hardware processor, or by time-slicing many hardware processors".14 Shared data needs locks or atomic types, such as AtomicLong, "A long value that may be updated atomically".15
  • C#. A program can "create additional threads to execute code in parallel or concurrently with the primary thread".16 The Interlocked class "Provides atomic operations for variables that are shared by multiple threads".17
  • Go. The runtime has no GIL. The GOMAXPROCS variable "limits the number of operating system threads that can execute user-level Go code simultaneously".18
  • Rust, C and C++. Threads are operating system threads that "run simultaneously".19 Shared data needs locks or atomic types. Rust atomic types "provide primitive shared-memory communication between threads".20 In C++, "If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined".21
PythonGitHub
import sys
import threading
import time

print("switch interval:", sys.getswitchinterval(), "seconds")


def spin(n):
    while n:
        n -= 1


def timed(target, arg, threads):
    workers = [threading.Thread(target=target, args=(arg,)) for _ in range(threads)]
    start = time.perf_counter()
    for w in workers:
        w.start()
    for w in workers:
        w.join()
    return time.perf_counter() - start


# The best of three runs, so that a busy machine changes the result less.
one = min(timed(spin, 1_000_000, 1) for _ in range(3))
four = min(timed(spin, 1_000_000, 4) for _ in range(3))
print("4 CPU-bound threads take at least twice as long as 1:", four >= 2 * one)

# time.sleep releases the GIL, as I/O does, so the four sleeps overlap.
sleeps = timed(time.sleep, 0.2, 4)
print("4 threads that sleep 0.2 s each finish in under 0.4 s:", sleeps < 0.4)

# The GIL does not make "total += 1" one step. Shared data still needs a lock.
total = 0
lock = threading.Lock()


def add(n):
    global total
    for _ in range(n):
        with lock:
            total += 1


workers = [threading.Thread(target=add, args=(100_000,)) for _ in range(4)]
for w in workers:
    w.start()
for w in workers:
    w.join()
print("total:", total)
Output
switch interval: 0.005 seconds
4 CPU-bound threads take at least twice as long as 1: True
4 threads that sleep 0.2 s each finish in under 0.4 s: True
total: 400000
  • Verdict: native. CPython, the standard Python, has a GIL, so "only one thread can execute Python code at once".
  • sys.getswitchinterval() gives the ideal length of the "timeslices" that running Python threads get, one after another. It is 5 milliseconds by default.
  • Four threads that each count down from 1,000,000 take about four times as long as one thread, because they take turns. The example checks only that they take at least twice as long, so that a busy machine does not change the output.
  • time.sleep releases the GIL, as I/O calls do, so four sleeps of 0.2 seconds overlap.
  • The GIL does not make total += 1 one step. The example uses a Lock for the shared total.
  • The output is for the default build. On a free-threaded build, the four CPU-bound threads can run in parallel, and the second line can print False.
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

int main() {
    // C++ threads have no global lock, so they can run at the same time.
    // A plain shared long changed by all threads would be a data race. std::atomic is not.
    std::atomic<long> total{0};
    {
        std::vector<std::jthread> threads;
        for (int t = 0; t < 4; t++) {
            threads.emplace_back([&total] {
                for (int i = 0; i < 100'000; i++) {
                    total.fetch_add(1, std::memory_order_relaxed);
                }
            });
        }
    }  // the jthread destructors join the threads here
    std::cout << "4 threads added 100000 each with std::atomic\n";
    std::cout << "total: " << total.load() << "\n";
}
Output
4 threads added 100000 each with std::atomic
total: 400000
  • Verdict: absent. C++ has no GIL. Threads run at the same time, and a plain shared long that they all change is a data race.
  • With std::atomic, "If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined".
  • The std::jthread objects are in a block, and their destructors join the threads before the total is printed.
JavaGitHub
import java.util.concurrent.atomic.AtomicLong;

public class Main {
  public static void main(String[] args) throws InterruptedException {
    // The JVM has no global interpreter lock: these threads can run on several cores at once.
    // So a shared counter must be atomic, or guarded by a lock.
    AtomicLong total = new AtomicLong();
    Thread[] threads = new Thread[4];
    for (int t = 0; t < threads.length; t++) {
      threads[t] =
          Thread.ofPlatform()
              .start(
                  () -> {
                    for (int i = 0; i < 100_000; i++) {
                      total.incrementAndGet();
                    }
                  });
    }
    for (Thread t : threads) {
      t.join();
    }
    System.out.println("4 threads added 100000 each with AtomicLong");
    System.out.println("total: " + total.get());
  }
}
Output
4 threads added 100000 each with AtomicLong
total: 400000
  • Verdict: absent. The JVM has no GIL. The Java Language Specification says that threads may run on "many hardware processors".
  • So two threads can change a shared counter at the same moment. An AtomicLong is "A long value that may be updated atomically", so each incrementAndGet is one atomic step.
using System;
using System.Threading;

// .NET has no global interpreter lock: these threads can run on several cores at once.
// So a shared counter must be changed with Interlocked, or under a lock.
long total = 0;
var threads = new Thread[4];
for (int t = 0; t < threads.Length; t++)
{
    threads[t] = new Thread(() =>
    {
        for (int i = 0; i < 100_000; i++)
        {
            Interlocked.Increment(ref total);
        }
    });
    threads[t].Start();
}
foreach (var t in threads)
{
    t.Join();
}
Console.WriteLine("4 threads added 100000 each with Interlocked.Increment");
Console.WriteLine($"total: {Interlocked.Read(ref total)}");
Output
4 threads added 100000 each with Interlocked.Increment
total: 400000
  • Verdict: absent. .NET has no GIL. A program can "create additional threads to execute code in parallel or concurrently with the primary thread".
  • Interlocked.Increment adds 1 as one atomic step. Interlocked.Read returns "a 64-bit value, loaded as an atomic operation".
JavaScriptGitHub
import { Worker } from "node:worker_threads";

// Each worker is a separate thread with its own JavaScript engine instance, so there is no lock
// that all threads share. The workers share only the memory of a SharedArrayBuffer.
const shared = new SharedArrayBuffer(4);
const total = new Int32Array(shared);

const workerCode = `
  const { workerData } = require("node:worker_threads");
  const total = new Int32Array(workerData);
  for (let i = 0; i < 100000; i++) Atomics.add(total, 0, 1);
`;

await Promise.all(
  Array.from({ length: 4 }, () =>
    new Promise((resolve, reject) => {
      const worker = new Worker(workerCode, { eval: true, workerData: shared });
      worker.once("exit", resolve);
      worker.once("error", reject);
    }),
  ),
);
console.log("4 workers added 100000 each with Atomics.add");
console.log("total:", Atomics.load(total, 0));
Output
4 workers added 100000 each with Atomics.add
total: 400000
  • Verdict: absent. JavaScript has no GIL. One thread runs the code of one engine instance, and a Worker is "an independent JavaScript execution thread". So there is no lock to share.
  • Workers can run CPU-bound code in parallel. Node.js says that workers "are useful for performing CPU-intensive JavaScript operations".
  • The workers share memory only through a SharedArrayBuffer. Atomics.add changes the shared total as one indivisible step, so no update is lost.
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	// Go has no global interpreter lock: up to GOMAXPROCS goroutines run Go code at the same time.
	// So a shared counter must be atomic, or guarded by a mutex.
	var total atomic.Int64
	var wg sync.WaitGroup
	for range 4 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for range 100_000 {
				total.Add(1)
			}
		}()
	}
	wg.Wait()
	fmt.Println("4 goroutines added 100000 each with atomic.Int64")
	fmt.Println("total:", total.Load())
}
Output
4 goroutines added 100000 each with atomic.Int64
total: 400000
  • Verdict: absent. Go has no GIL. The GOMAXPROCS variable "limits the number of operating system threads that can execute user-level Go code simultaneously". By default, the runtime picks it from the number of logical CPUs of the machine and the limits of the process.
  • atomic.Int64 makes each Add one atomic step. A plain int64 with total++ in each goroutine would be a data race.
RustGitHub
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread;

fn main() {
    // Rust threads are operating system threads with no global lock, so they can run at the same time.
    // The compiler does not allow a plain shared counter here: it must be atomic, or behind a Mutex.
    let total = AtomicU64::new(0);
    thread::scope(|s| {
        for _ in 0..4 {
            s.spawn(|| {
                for _ in 0..100_000 {
                    total.fetch_add(1, Ordering::Relaxed);
                }
            });
        }
    });
    println!("4 threads added 100000 each with AtomicU64");
    println!("total: {}", total.load(Ordering::Relaxed));
}
Output
4 threads added 100000 each with AtomicU64
total: 400000
  • Verdict: absent. Rust threads are operating system threads, and the Rust book describes them as independent parts of a program "that run simultaneously".
  • Atomic types "provide primitive shared-memory communication between threads", so the example uses AtomicU64 for the shared total. Ordering::Relaxed is enough for a counter that the main thread reads after the joins.
  • Process-based parallelism. Each process has its own interpreter and its own GIL, so processes run in parallel. This is the usual answer to the GIL for CPU-bound work.39
  • One lock for each ractor. Ruby holds one GVL for each ractor, so code in different ractors runs in parallel, and objects move between ractors as messages.11
  • Giant locks and Green threads. Wikipedia lists both as ideas related to the GIL.2

Pitfalls

  • Thinking that the GIL makes code thread-safe. The GIL protects the data of the interpreter, not the data of your program. A step such as total += 1 reads the value, adds 1 and writes the result, and another thread can run between these steps. The glossary says that global state shared between threads "typically requires synchronization to avoid race conditions and data races".1 The Python example uses a Lock for its total. The free-threading guide also recommends "the threading.Lock or other synchronization primitives instead of relying on the internal locks of built-in types".8
  • Threads for CPU-bound work. More threads do not make pure Python calculations faster under the GIL. Wikipedia says that there is "likely to be very little increase in speed" on a multiprocessor machine, and that a CPU-bound thread can cause "a significant slowdown, even on single processors".2 Use processes, or a library that releases the GIL.31
  • Assuming that the GIL is always there. On a free-threaded build, code that worked only because of the GIL can fail. Test threaded code on both builds.8
  • Extensions that turn the GIL back on. In the free-threaded build, importing an extension module that does not support free threading can re-enable the GIL, and a warning is printed.8

Cost

  • With one thread. A GIL makes code with one thread fast, because the interpreter takes one lock instead of many small ones.2 The free-threaded build of CPython gives up some of this speed.8
  • With many threads. CPU-bound Python threads under the GIL run no faster than one thread, and switching between them adds overhead.32 I/O-bound threads lose little, because they release the GIL while they wait.1
  • Processes instead. Processes avoid the GIL, but data must go between them through queues or pipes, or be put in shared memory.9

History

  • 2011. Python 3.2, released on 20 February 2011, rewrote the GIL. A switch interval in seconds replaced the old "check interval", and its default became 5 milliseconds.5
  • 2023. PEP 703, "Making the Global Interpreter Lock Optional in CPython", was accepted on 24 October 2023.6
  • 2024. Python 3.13, released in October 2024, added "experimental support for running in a free-threaded mode, with the global interpreter lock (GIL) disabled".7

References

  1. Python documentation, Glossary, global interpreter lock; global state
  2. Wikipedia, Global interpreter lock, introduction; Technical background concepts; Advantages; Drawbacks; Examples
  3. The Python Standard Library, threading, CPython implementation detail; GIL and performance considerations
  4. The Python Standard Library, sys, setswitchinterval
  5. What's New In Python 3.2, Multi-threading
  6. PEP 703: Making the Global Interpreter Lock Optional in CPython, header; Abstract; Motivation
  7. What's New In Python 3.13, introduction; Free-threaded CPython
  8. Python HOWTOs, Python support for free threading, introduction; The global interpreter lock in free-threaded Python; Thread safety; Single-threaded performance
  9. The Python Standard Library, multiprocessing, Introduction; Exchanging objects between processes; Sharing state between processes
  10. Ruby documentation, Ractor - Ruby's Actor-like concurrent abstraction, Summary
  11. Ruby documentation, class Ractor, class description; Ractors vs threads
  12. Node.js documentation, Worker threads, introduction; Class Worker
  13. MDN Web Docs, Atomics, introduction
  14. The Java Language Specification, Java SE 21, Chapter 17, Threads and Locks, introduction
  15. Java SE 21 API, java.util.concurrent.atomic.AtomicLong, class description
  16. Microsoft Learn, Threads and threading, Multithreading; When to use multiple threads
  17. Microsoft Learn, Interlocked class, class description; Read
  18. Go standard library, package runtime, Environment Variables; func GOMAXPROCS
  19. The Rust Programming Language, Using Threads to Run Code Simultaneously, introduction
  20. Rust standard library, module std::sync::atomic, module description
  21. cppreference, std::atomic, description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/44BD7Y/text.yaml