Skip to content

Free-threaded build: a blocking threading.Lock hand-off costs 40 sched_yield() calls, and tens of milliseconds on an oversubscribed machine #162421

Open

Description

@Toilal

Bug report

Bug description:

On the free-threaded build, every blocking acquire of a contended PyMutex first calls _Py_yield() (sched_yield() on Linux) MAX_SPIN_COUNT (40) times before parking (Python/lock.c, _PyMutex_LockTimed). The lock word v is not reloaded inside that loop (the reload of gh-146064 was reverted by gh-157914), so a waiter that has started spinning always completes the 40 yields, even when the lock was released right after the first one.

On an idle machine sched_yield() returns at once and the cost is ~40 µs per hand-off. On a machine whose cores are oversubscribed, each sched_yield() can hand the CPU to another runnable process for a whole time slice, and a hand-off between two Python threads goes from ~0.1 ms to tens of milliseconds. The default build (MAX_SPIN_COUNT = 0) does not degrade this way, and PYTHON_GIL=1 on the free-threaded build does not help (the spin count is a compile-time constant).

Everything that waits on a threading.Lock is affected: threading.Event, threading.Condition, queue.Queue, and therefore e.g. anyio's worker threads (anyio.to_thread.run_sync), which wait on a queue.Queue.

Several candidate patches were measured on 3.14 and main. One (D5) brings the saturated hand-off back to the default build's level and keeps the gh-157914 shared-dict case at its current speed, at a cost of ~20% in one lockbench setting; see Patches tried below.

Reproducer:

import os, sys, threading, time

N = 2000

def lock_pingpong():
    a, b = threading.Lock(), threading.Lock()
    a.acquire(); b.acquire()
    def echo():
        for _ in range(N):
            a.acquire(); b.release()
    t = threading.Thread(target=echo); t.start()
    start = time.perf_counter()
    for _ in range(N):
        a.release(); b.acquire()
    t.join()
    return time.perf_counter() - start

print(sys.version.split()[0], "gil", getattr(sys, "_is_gil_enabled", lambda: True)(), "load", os.getloadavg()[0])
print(f"{lock_pingpong() / N * 1e6:.0f} us/round trip")

CPython 3.14.10, Linux 7.0, 16 cores; "loaded" means beside 48 busy loops (for i in $(seq 48); do sh -c 'while :; do :; done' & done):

threading.Lock round trip default build free-threaded
idle machine 9 µs 41 µs
loaded 109 µs 88–164 ms

With PYTHON_GIL=1 on the free-threaded build, the loaded round trip is still 73 ms.

strace -f -c -e trace=sched_yield on the same script, idle machine: 0 calls on the default build, ~159,000 on the free-threaded one (~80 per round trip: two blocking acquires × 40).

The cost comes from the spin strategy, not from threads or the kernel. The same ping-pong in C, with a lock that either parks on a futex at once or first calls sched_yield() 40 times without reloading (as _PyMutex_LockTimed does), behaves like the default build in the first case and like the free-threaded build in the second. Same machine, run twice, at a load average of ~32 on 16 cores (a mixed workload rather than pure busy loops, hence the smaller gap than in the table above):

loaded, round trip µs
C, park at once 24 – 66
Python, default build 74 – 90
C, 40 sched_yield() then park 578 – 632
Python, free-threaded build 525 – 1071
C reproducer (cc -O2 -pthread pingpong.c && ./pingpong 0 && ./pingpong 40 && ./pingpong 40 reload)
#include <pthread.h>
#include <sched.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <linux/futex.h>
#include <sys/syscall.h>
#include <unistd.h>
#define N 2000
static int yields, reload;
/* a lock that calls sched_yield() `yields` times (re-reading the lock after each one if `reload`), then parks on a futex */
typedef struct { _Atomic int v; } lk;
static void lk_lock(lk *l) {
    int z = 0;
    if (atomic_compare_exchange_strong(&l->v, &z, 1)) return;
    for (int i = 0; i < yields; i++) { sched_yield(); if (reload && atomic_load(&l->v) == 0) { z = 0; if (atomic_compare_exchange_strong(&l->v, &z, 1)) return; } }
    while (atomic_exchange(&l->v, 2) != 0) syscall(SYS_futex, &l->v, FUTEX_WAIT_PRIVATE, 2, NULL, NULL, 0);
}
static void lk_unlock(lk *l) {
    if (atomic_exchange(&l->v, 0) == 2) syscall(SYS_futex, &l->v, FUTEX_WAKE_PRIVATE, 1, NULL, NULL, 0);
}
static lk a = {1}, b = {1};
static void *echo(void *_) { for (int i = 0; i < N; i++) { lk_lock(&a); lk_unlock(&b); } return NULL; }
int main(int argc, char **argv) {
    yields = atoi(argv[1]); reload = argc > 2;
    pthread_t t; struct timespec s, e;
    pthread_create(&t, NULL, echo, NULL);
    clock_gettime(CLOCK_MONOTONIC, &s);
    for (int i = 0; i < N; i++) { lk_unlock(&a); lk_lock(&b); }
    pthread_join(t, NULL);
    clock_gettime(CLOCK_MONOTONIC, &e);
    printf("C, %2d sched_yield before parking%s: %8.0f us/round trip\n", yields,
           reload ? ", reloading" : "", ((e.tv_sec - s.tv_sec) * 1e9 + (e.tv_nsec - s.tv_nsec)) / N / 1e3);
}

Primitives that do not wait on a PyMutex-backed lock are much less affected under the same load:

loaded, per hand-off default build free-threaded
queue.SimpleQueue ping-pong 22 µs 32 µs
asyncio.to_thread (executor, SimpleQueue) 0.3–0.8 ms 2–3.5 ms
anyio.to_thread.run_sync (worker on queue.Queue) 0.3–0.7 ms 3.3–15.8 ms

In a real application (an asyncio HTTP service streaming a 32 MiB file chunk by chunk through anyio worker threads, client and server on the same machine), under the same load the transfer takes 2.1 s on the default build and 94.6 s on the free-threaded one (a second free-threaded run did not finish in 15 minutes). Moving the per-chunk hops from anyio's workers to a ThreadPoolExecutor brought it to 54–66 s, so the Lock hand-off is a large part of the gap but not all of it.

How other runtimes spin

None of the mutexes below give the CPU back to the OS while spinning: they spin a bounded number of times with a CPU pause hint, re-reading the lock word each time, then sleep on a futex. Only CPython's free-threaded PyMutex calls sched_yield() in its spin.

spin before sleeping yields to the OS?
CPython 3.14 free-threaded PyMutex MAX_SPIN_COUNT = 40 iterations of _Py_yield() = sched_yield(), lock word read once, before the loop yes, 40 times
glibc pthread_mutex_lock, default type none: PTHREAD_MUTEX_TIMED_NP goes straight to the futex lock no
glibc PTHREAD_MUTEX_ADAPTIVE_NP exponential backoff of atomic_spin_nop() = pause on x86, lock re-read every round, capped by glibc.pthread.mutex_spin_count (100) no
Rust std::sync::Mutex (futex) 100 iterations of spin_loop(), state re-read every iteration, then futex_wait no
Go sync.Mutex at most 4 × 30 procyield = PAUSE, and only on a multicore machine with another P running and an empty local run queue no

(Links are pinned: CPython at the 3.14 branch head, the others at their default branch head as of this report.)

The pitfall is a known one. Linus Torvalds, on user-space spinning, 2020-01-04:

And no, adding random "sched_yield()" calls while you're spinning on the spinlock will not really help. It will easily result in scheduling storms while people are yielding to all the wrong processes.

PyMutex is not a pure spinlock (it does park eventually), so this applies to its spin phase only, but that phase is exactly what the measurements above isolate.

Prior work, and why this case is different

The WebKit post measured 40 yields as optimal on a throughput microbenchmark (4 threads contending for one lock). Two things have changed since, both in WebKit itself:

  • Its spin re-reads the lock word on every iteration (LockAlgorithm::lockSlow loads the lock at the top of each pass), which CPython's loop does not do.
  • In September 2026 WebKit stopped spinning with sched_yield() on Linux (249ede976f, "sched_yield is not so helpful, since it isn't guaranteed to actually yield [...] and can cause deadlocks"). Its Linux spin is now 6 exponential steps of pause and 0 yields before parking; only non-ARM Darwin and Windows keep 40 yield steps (Darwin's yield being thread_switch, per the commit message).

What this report adds is the oversubscribed regime: once every core has a runnable process, each sched_yield() is a time slice handed away, which neither the WebKit measurements nor lockbench cover. Same C model, both threads and 6 busy loops pinned to 2 cores (taskset -c 14,15):

loaded, 2 pinned cores, round trip 1st run 2nd run
C, park at once 125 µs 132 µs
Python, default build 78 µs 96 µs
C, 40 sched_yield() then park, re-reading the lock after each yield (the gh-146064 approach) 9.0 ms 8.2 ms
C, 40 sched_yield() then park, no re-read (CPython's loop) 309 ms 295 ms
Python, free-threaded build 289 ms 308 ms

Patches tried

All changes are to the spin in _PyMutex_LockTimed. They were measured on one laptop (Ryzen 7 PRO 5850U, 8 cores / 16 threads, Linux 7.0, on mains power), built with the same flags as the unpatched build they are compared with (./configure --disable-gil, no PGO/LTO unless stated). "Idle" means the 1-minute load stayed under 1.0 for two minutes before the run (1.5 for the 3.14 runs); "saturated" means both threads and 6 busy loops pinned to 2 cores (taskset -c 14,15). Builds alternate within a run; ranges are over 2 to 10 runs.

  • A. WebKit's Linux spin: 6 exponential steps of pause (63 in all), re-reading the lock after each step, no yield.
  • B. The same with steps capped at 32 pauses, for up to 40 µs.
  • C. The current 40 sched_yield() calls, but park once the spin has lasted 100 µs.
  • D. C, plus: a sched_yield() lasting more than 50 µs (the core went to another runnable thread) parks at once, and makes the thread's next 256 contended acquisitions park without spinning (a thread-local counter).
  • D2. D with a 500 µs threshold. (D3, skipping 64 acquisitions instead of 256, and D4, one clock read per yield instead of two, measured the same as D2 or worse.)
  • D5. D2, reading the clock after the first yield and then every 8th: 5 reads per wait instead of 80. The diff is at the end.

On main (1cc5802)

default build unpatched A B C D D2 D5
Lock ping-pong, idle (µs) 8 – 10 28 – 38 6 – 9 0 33 – 37 34 – 39 31 – 36 29 – 31
gh-157914 shared dict, idle (s) 0.198 – 0.251 0.314 – 0.411 1.57 – 1.75 0.87 – 0.97 0.344 – 0.365 0.352 – 0.425 0.309 – 0.388 0.324 – 0.395
Lock ping-pong, saturated (µs) 29 – 169 224,285 – 336,110 50 – 64 234 – 247 5,610 – 8,210 29 – 169 14 – 62 15 – 61
gh-157914 shared dict, saturated (s) 1.05 – 1.19 2.01 – 2.70 0.84 – 0.97 1.06 – 1.12 1.12 – 1.30 0.75 – 1.14 0.73 – 2.24, median 1.05 0.96 – 2.47, median 1.10
sched_yield() calls, idle ping-pong 0 159,880 0 0 18,071 9,339 15,768 – 19,255

Tools/lockbench/lockbench.py, PyMutex acquisitions per second (the two contention settings are those of gh-157914: --work-inside 5 --work-outside 5, and --work-inside 5 --work-outside 50 --num-locks 24 --acquisitions 3 --random-locks):

setting, 10 threads unpatched A B C D D5
--work-inside 1 109k – 111k 9.1k – 9.2k 12.5k – 12.6k 98k – 108k 111k
--work-inside 10 38k – 40k 6.5k 8.5k – 9.3k 36k 36k – 38k
--work-inside 100 4.3k – 4.5k 1.8k – 1.9k 2.2k – 2.3k 4.3k – 4.4k 4.2k – 4.4k
high contention 54.7k – 57.7k 6.2k – 6.3k 9.5k 57.8k – 58.6k 54.9k – 60.1k 56.8k – 57.4k
low contention 49.5k – 51.0k 108k – 111k 172k – 173k 50.2k – 50.8k 50.2k – 50.3k 49.6k – 51.2k

The D variants lose in one setting, a 100-iteration critical section with 2 to 4 threads. Medians of 6 runs in one session; "control" is the unpatched loop plus two clock reads around each yield whose result is never used:

setting unpatched C control D2 D5
--work-inside 100, 2 threads 11.0k 10.2k 9.8k 8.1k 8.8k
--work-inside 100, 4 threads 8.2k 7.9k 6.8k 6.6k 6.6k
--work-inside 10, 4 threads 63.8k 64.8k 63.9k 61.4k 61.2k
--work-inside 1, 4 threads 170k 163k 170k 169k 171k

I could not pin that cost to one mechanism:

  • The adaptive part is not exercised there: with counters added, the slow-yield branch fires 0 to 2 times per run and skips at most 512 acquisitions.
  • Throughput follows the number of parks: 130k–285k per run for C, 405k–949k for the unpatched loop, 425k–1,076k for D2. Each wasted wake-up costs the lock holder a futex call.
  • The control build loses 11–17% with no logic at all, while D5, which reads the clock 16 times less often than D2, loses about as much as D2. This setting reacts to small changes in the loop's timing, in both directions: with the counters compiled in, the control build was faster than the unpatched one.

PGO+LTO builds (--enable-optimizations --with-lto), same session:

unpatched D5
Lock ping-pong, idle (µs) 29 – 32 29 – 30
gh-157914 shared dict, idle (s) 0.254 – 0.325 0.245 – 0.317
Lock ping-pong, saturated (µs) 224,290 – 224,475 30 – 1,990 (30, 325, 1,990)
gh-157914 shared dict, saturated (s) 1.31 – 2.01 0.85 – 1.15

lockbench is not meaningful on PGO builds: the training run never calls benchmark_locks, so GCC compiles its loop as cold code, and even single-thread figures halve (60k against 140k). PGO also splits _PyMutex_LockTimed into hot and cold parts following that profile.

On 3.14.10 (A to D)

default build 3.14t A B C D
Lock ping-pong, idle (µs) 8 – 13 32 – 36 2 – 9 0 35 – 38 35 – 41
gh-157914 shared dict, idle (s) 0.357 – 0.432 1.792 – 2.132 0.918 – 1.117 0.356 – 0.437 0.357 – 0.467
Lock ping-pong, saturated (µs) 29 – 62 224,095 – 224,435 54 – 64 183 – 299 5,580 – 5,610 48 – 51
gh-157914 shared dict, saturated (s) 2.38 – 2.64 1.22 – 1.26 1.19 – 1.63 1.37 – 1.50 1.02 – 1.11

lockbench (3.14 version) gave the same picture as on main.

What this shows:

  • A and B (spinning on pause, as WebKit and the other runtimes above do) fix the saturated case but cost 2–11x under contention on an idle machine, including the shared-dict case Performance regression from PyMutex spin-loop reloading in free-threaded builds #157914 reverted gh-135871: Reload lock internal state while spinning in PyMutex_LockTimed #146064 over. On an idle machine the 40 yields are a ~40 µs wait, and 63 pauses are far shorter, so contended threads park much more often. The exception is the low-contention setting, where A and B are 2–3.4x faster: there the waiter that cannot see the lock being released (no reload) waits out the whole spin for nothing. None of C, D or D5 changes that.
  • C keeps the idle behaviour and cuts the saturated hand-off 30–40x, but the first yield that gives the core away still costs a time slice (~5–8 ms here).
  • D5 keeps the idle behaviour on everything above but one lockbench setting (−20% with a 100-iteration critical section and 2 to 4 threads, on non-PGO builds), and brings both the saturated hand-off and the saturated shared dict to the default build's level.

The thresholds (100 µs budget, 500 µs slow yield, 256 skipped acquisitions, a read every 8 yields) are not tuned beyond the variants above (50 µs and 64 measured the same); only x86-64 Linux was measured.

Patch D5 (against main, 1cc5802)
diff --git a/Python/lock.c b/Python/lock.c
index 59dfe772a03..8412fe27d56 100644
--- a/Python/lock.c
+++ b/Python/lock.c
@@ -31,6 +31,18 @@ static const int MAX_SPIN_COUNT = 40;
 static const int MAX_SPIN_COUNT = 0;
 #endif
 
+// A spin that has lasted longer than MAX_SPIN_NS parks, yields left or not.
+// Yields that lasted longer than SLOW_YIELD_NS handed the core to another
+// runnable thread: the machine is oversubscribed, and each further yield could
+// cost a whole time slice. The thread then parks at once, and parks without
+// spinning on its next SPIN_SKIP contended acquisitions. The clock is read
+// after the first yield, then every YIELDS_PER_CLOCK_READ yields.
+static const int YIELDS_PER_CLOCK_READ = 8;
+static const PyTime_t MAX_SPIN_NS = 100*1000;
+static const PyTime_t SLOW_YIELD_NS = 500*1000;
+static const int SPIN_SKIP = 256;
+static _Py_thread_local int spins_to_skip = 0;
+
 struct mutex_entry {
     // The time after which the unlocking thread should hand off lock ownership
     // directly to the waiting thread. Written by the waiting thread.
@@ -79,6 +91,11 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
     };
 
     Py_ssize_t spin_count = 0;
+    PyTime_t last_read = now;
+    if (spins_to_skip > 0) {
+        spins_to_skip--;
+        spin_count = MAX_SPIN_COUNT;
+    }
     for (;;) {
         if ((v & _Py_LOCKED) == 0) {
             // The lock is unlocked. Try to grab it.
@@ -92,6 +109,18 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
             // Spin for a bit.
             _Py_yield();
             spin_count++;
+            if (spin_count % YIELDS_PER_CLOCK_READ == 1) {
+                PyTime_t spun;
+                (void)PyTime_MonotonicRaw(&spun);
+                if (last_read != 0 && spun - last_read > SLOW_YIELD_NS) {
+                    spins_to_skip = SPIN_SKIP;
+                    spin_count = MAX_SPIN_COUNT;
+                }
+                else if (spun - now > MAX_SPIN_NS) {
+                    spin_count = MAX_SPIN_COUNT;
+                }
+                last_read = spun;
+            }
             continue;
         }
 
@@ -122,6 +151,8 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
 
         int ret = _PyParkingLot_Park(&m->_bits, &newv, sizeof(newv), timeout,
                                      &entry, (flags & _PY_LOCK_DETACH) != 0);
+        // The time parked is not a yield.
+        last_read = 0;
         if (ret == Py_PARK_OK) {
             if (entry.handed_off) {
                 // We own the lock now. thread.Lock allows other threads

CPython versions tested on:

3.14, CPython main branch

Measured on 3.14.10 and on main at 1cc5802.

Operating systems tested on:

Linux

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions