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.

The patches, all to Python/lock.c; the 3.14.10 runs used the same changes.

Patch A (against main, 1cc5802)

Branch: main-lock-spin.

diff --git a/Python/lock.c b/Python/lock.c
index 59dfe772a03..48ff1b51b7a 100644
--- a/Python/lock.c
+++ b/Python/lock.c
@@ -26,11 +26,14 @@ static const PyTime_t TIME_TO_BE_FAIR_NS = 1000*1000;
 // `--disable-gil` builds because it is unlikely to be helpful if the GIL is
 // enabled.
 #ifdef Py_GIL_DISABLED
-static const int MAX_SPIN_COUNT = 40;
+static const int MAX_SPIN_COUNT = 6;
 #else
 static const int MAX_SPIN_COUNT = 0;
 #endif
 
+// Spin step N waits 2**N CPU pause hints and then re-reads the lock: a
+// spinning waiter never hands its core to the scheduler.
+
 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.
@@ -50,6 +53,18 @@ _Py_yield(void)
 #endif
 }
 
+static inline void
+_Py_cpu_pause(void)
+{
+#if defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__))
+    __asm__ volatile("pause" ::: "memory");
+#elif defined(__GNUC__) && defined(__aarch64__)
+    __asm__ volatile("yield" ::: "memory");
+#else
+    _Py_yield();
+#endif
+}
+
 PyLockStatus
 _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
 {
@@ -89,9 +104,12 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
         }
 
         if (!(v & _Py_HAS_PARKED) && spin_count < MAX_SPIN_COUNT) {
-            // Spin for a bit.
-            _Py_yield();
+            // Spin for a bit, then look at the lock again.
+            for (int i = 1 << spin_count; i > 0; i--) {
+                _Py_cpu_pause();
+            }
             spin_count++;
+            v = _Py_atomic_load_uint8_relaxed(&m->_bits);
             continue;
         }
 
Patch B (against main, 1cc5802)

Branch: main-lock-pause-budget.

diff --git a/Python/lock.c b/Python/lock.c
index 59dfe772a03..95c8d36abc1 100644
--- a/Python/lock.c
+++ b/Python/lock.c
@@ -26,11 +26,15 @@ static const PyTime_t TIME_TO_BE_FAIR_NS = 1000*1000;
 // `--disable-gil` builds because it is unlikely to be helpful if the GIL is
 // enabled.
 #ifdef Py_GIL_DISABLED
-static const int MAX_SPIN_COUNT = 40;
+static const int MAX_SPIN_COUNT = 1000;
 #else
 static const int MAX_SPIN_COUNT = 0;
 #endif
 
+// Spin with CPU pause hints, re-reading the lock between steps, for at most
+// this long before parking.
+static const PyTime_t MAX_SPIN_NS = 40*1000;
+
 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.
@@ -50,6 +54,18 @@ _Py_yield(void)
 #endif
 }
 
+static inline void
+_Py_cpu_pause(void)
+{
+#if defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__))
+    __asm__ volatile("pause" ::: "memory");
+#elif defined(__GNUC__) && defined(__aarch64__)
+    __asm__ volatile("yield" ::: "memory");
+#else
+    _Py_yield();
+#endif
+}
+
 PyLockStatus
 _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
 {
@@ -89,9 +105,14 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
         }
 
         if (!(v & _Py_HAS_PARKED) && spin_count < MAX_SPIN_COUNT) {
-            // Spin for a bit.
-            _Py_yield();
-            spin_count++;
+            // Spin for a bit, then look at the lock again.
+            for (int i = 1 << (spin_count < 5 ? spin_count : 5); i > 0; i--) {
+                _Py_cpu_pause();
+            }
+            PyTime_t spun;
+            (void)PyTime_MonotonicRaw(&spun);
+            spin_count = (spun - now > MAX_SPIN_NS) ? MAX_SPIN_COUNT : spin_count + 1;
+            v = _Py_atomic_load_uint8_relaxed(&m->_bits);
             continue;
         }
 
Patch C (against main, 1cc5802)

Branch: main-lock-yield-budget.

diff --git a/Python/lock.c b/Python/lock.c
index 59dfe772a03..d6a28dfdb9b 100644
--- a/Python/lock.c
+++ b/Python/lock.c
@@ -31,6 +31,10 @@ static const int MAX_SPIN_COUNT = 40;
 static const int MAX_SPIN_COUNT = 0;
 #endif
 
+// A spin that has lasted longer than this parks, yields left or not: on an
+// oversubscribed machine a single sched_yield() can last a whole time slice.
+static const PyTime_t MAX_SPIN_NS = 100*1000;
+
 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.
@@ -92,6 +96,11 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
             // Spin for a bit.
             _Py_yield();
             spin_count++;
+            PyTime_t spun;
+            (void)PyTime_MonotonicRaw(&spun);
+            if (spun - now > MAX_SPIN_NS) {
+                spin_count = MAX_SPIN_COUNT;
+            }
             continue;
         }
 
Patch D (against main, 1cc5802)

Branch: main-lock-adaptive-spin.

D2 is this patch with SLOW_YIELD_NS = 500*1000 (main-lock-adaptive-spin-500us); D3 is D2 with SPIN_SKIP = 64 (main-lock-adaptive-spin-500us-64).

diff --git a/Python/lock.c b/Python/lock.c
index 59dfe772a03..b748b77d8b6 100644
--- a/Python/lock.c
+++ b/Python/lock.c
@@ -31,6 +31,16 @@ 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.
+// A single yield 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.
+static const PyTime_t MAX_SPIN_NS = 100*1000;
+static const PyTime_t SLOW_YIELD_NS = 50*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 +89,10 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
     };
 
     Py_ssize_t spin_count = 0;
+    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.
@@ -90,8 +104,18 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
 
         if (!(v & _Py_HAS_PARKED) && spin_count < MAX_SPIN_COUNT) {
             // Spin for a bit.
+            PyTime_t before, after;
+            (void)PyTime_MonotonicRaw(&before);
             _Py_yield();
+            (void)PyTime_MonotonicRaw(&after);
             spin_count++;
+            if (after - before > SLOW_YIELD_NS) {
+                spins_to_skip = SPIN_SKIP;
+                spin_count = MAX_SPIN_COUNT;
+            }
+            else if (after - now > MAX_SPIN_NS) {
+                spin_count = MAX_SPIN_COUNT;
+            }
             continue;
         }
 
Patch D4 (against main, 1cc5802)

Branch: main-lock-adaptive-spin-1clock.

diff --git a/Python/lock.c b/Python/lock.c
index 59dfe772a03..12fcb3c5048 100644
--- a/Python/lock.c
+++ b/Python/lock.c
@@ -31,6 +31,16 @@ 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.
+// A single yield 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.
+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 +89,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 +107,16 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
             // Spin for a bit.
             _Py_yield();
             spin_count++;
+            PyTime_t yielded;
+            (void)PyTime_MonotonicRaw(&yielded);
+            if (yielded - last_read > SLOW_YIELD_NS) {
+                spins_to_skip = SPIN_SKIP;
+                spin_count = MAX_SPIN_COUNT;
+            }
+            else if (yielded - now > MAX_SPIN_NS) {
+                spin_count = MAX_SPIN_COUNT;
+            }
+            last_read = yielded;
             continue;
         }
 
@@ -122,6 +147,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);
+        // A spin after a wake-up must not count the time parked as a yield.
+        (void)PyTime_MonotonicRaw(&last_read);
         if (ret == Py_PARK_OK) {
             if (entry.handed_off) {
                 // We own the lock now. thread.Lock allows other threads
Patch D5 (against main, 1cc5802)

Branch: main-lock-adaptive-spin-sparse-clock.

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

  1. added
    interpreter-core
    performance
    type-bug
    on Nov 22, 2026
  2. alexeyshockov commented on Nov 26, 2026

    @alexeyshockov

    A server-side case of the same spin, with a stdlib-only reproducer, and a measurement that isolates the sched_yield() calls themselves.

    A thread-per-connection HTTP/1.1 keep-alive server (below), 64 keep-alive connections, the server pinned to 3 CPUs and the load generator (oha) to a fourth. Once the connection threads' Python work keeps the 3 CPUs busy, new connections wait seconds to be accepted: the accepting thread's Thread.start() waits for the new thread's _started event, a blocking Lock.acquire(), and each of its sched_yield() calls puts it behind the runnable connection threads.

    10 s window after a 5 s warm-up, every request's latency recorded by oha, 3 passes each:

    CPython 3.15.2 free-threaded worst request requests over 1 s requests in 10 s
    PYTHON_GIL=0 3.4–4.5 s 20–22 1.37–1.41 M
    PYTHON_GIL=0, sched_yield() a no-op (LD_PRELOAD) 32–43 ms 0 1.39–1.41 M
    PYTHON_GIL=1 80–92 ms 0 0.54 M

    The no-op is int sched_yield(void) { return 0; } built with gcc -O2 -shared -fPIC: the waiter still goes through the 40 iterations and still parks, it just stops handing its CPU away on each one. That alone removes the tail at the same throughput, so for this case a spin that does not yield to the OS (as in gh-144586 or the patches in the issue) would be enough. That last part is an inference: I have not built CPython with those patches.

    On a variant of the same server with more Python work per request (worst request 9.5–9.9 s), the accepting thread, sampled from /proc every 30 ms over two 10 s windows:

    • runnable in 662 of 663 samples, and in each window ran 8 ms while waiting 9.98 s on the run queue (schedstat);
    • perf record -e context-switches --call-graph fp -t <tid>: 345 of its 364 switches are __sched_yield called from _thread_lock_acquire_impl;
    • meanwhile the listening socket's accept queue (ss -ltn) held 46–55 established connections, and each connection was answered within milliseconds of its accept(), so every slow request was a connection waiting to be accepted.

    Prestarting the connection threads (no Thread.start() under load) shortens the tail to 1.5–2.2 s but does not remove it; I have not traced which waits are left.

    Environment: CPython 3.15.2 free-threaded (python-build-standalone 20261124, x86_64, install_only), Linux 7.3.4 (Debian), Intel Core i5-11320H (4 cores), performance governor not pinned.

    Reproducer (repro_server.py and the run script)
    import os, socket, sys, threading
    
    WORK = int(os.environ.get("WORK", "600"))
    RESPONSE = b"HTTP/1.1 200 OK\r\ncontent-length: 4\r\n\r\npong"
    
    
    def serve(conn):
        buffer = b""
        lookups = {b"host": b"x"}
        with conn:
            try:
                while True:
                    while b"\r\n\r\n" not in buffer:
                        data = conn.recv(65536)
                        if not data:
                            return
                        buffer += data
                    _, _, buffer = buffer.partition(b"\r\n\r\n")
                    for _ in range(WORK):
                        lookups.get(b"host")
                    conn.sendall(RESPONSE)
            except OSError:
                pass
    
    
    listener = socket.create_server(("127.0.0.1", int(sys.argv[1])), backlog=4096)
    while True:
        conn, _ = listener.accept()
        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        threading.Thread(target=serve, args=(conn,), daemon=True).start()
    PYTHON_GIL=0 taskset -c 0,1,2 python3.15t repro_server.py 18801 &
    sleep 1
    taskset -c 3 oha --no-tui -z 5s -c 64 --worker-threads 1 http://127.0.0.1:18801/ > /dev/null   # warm-up
    taskset -c 3 oha --no-tui -z 10s -c 64 --worker-threads 1 --db-url repro.db http://127.0.0.1:18801/ > /dev/null
    python3 -c "import sqlite3; db = sqlite3.connect('repro.db'); print(db.execute('select max(end - start), (select count(*) from oha where end - start > 1) from oha').fetchone())"
  3. alexeyshockov commented on Nov 26, 2026

    @alexeyshockov

    A follow-up on queue.SimpleQueue, which the issue lists as much less affected. Its blocking get() does not spin before parking, but it goes through the same spin on the way back: a woken getter re-attaches its thread state, which resumes the critical section on the queue, and that lock can still be held by the thread whose put() woke it (both are @critical_section in Modules/_queuemodule.c; put() calls _PyParkingLot_Unpark inside it, and get() parks with detach=1). Under oversubscription that contended PyMutex_Lock spins with sched_yield() like any other, so most hand-offs are fast and an occasional one takes hundreds of milliseconds.

    perf record -e context-switches --call-graph fp on the ping-pong below (8 pairs, beside 9 busy loops on the same 3 CPUs): 127 of the 203 sched_yield calls in 4 s are

    __sched_yield < PyMutex_Lock < _PyMutex_Lock < _PyCriticalSection_Resume < _PyThreadState_Attach
      < PyEval_AcquireThread < _PyParkingLot_Park < _queue_SimpleQueue_get_impl
    

    (the rest are the main thread's join()).

    PAIRS pairs of threads, each handing one item back and forth over two SimpleQueues for 5 s, pinned to 3 CPUs; 2 runs each, with sched_yield() made a no-op through LD_PRELOAD as in my previous comment:

    CPython 3.15.2 free-threaded, PYTHON_GIL=0 sched_yield() as is: p99.9 / max no-op: p99.9 / max
    8 pairs, nothing else running 2.2–2.3 ms / 11–12 ms 0.03 ms / 1.7–3.2 ms
    1 pair, beside 9 busy loops 4.4–116 ms / 5.6–448 ms 2.8–4.8 ms / 5.6–8.0 ms
    8 pairs, beside 9 busy loops 3.7–5.6 ms / 394–628 ms 5.6 ms / 8.6–10.4 ms

    So a primitive that parks in the parking lot without spinning first still meets the spin on wake-up, wherever the
    woken thread re-takes an object's critical section that its waker holds. A fix to _PyMutex_LockTimed's spin covers this path too; one that only changed the waits before parking would not.

    Environment as before: CPython 3.15.2 free-threaded (python-build-standalone 20261124, x86_64, install_only), Linux 7.3.4 (Debian), Intel Core i5-11320H (4 cores), performance governor not pinned.

    Reproducer (simplequeue_pingpong.py PAIRS SECONDS)
    import queue, statistics, sys, threading, time
    
    pairs, seconds = int(sys.argv[1]), float(sys.argv[2])
    stop = False
    trips = [[] for _ in range(pairs)]
    
    
    def echo(inbox, outbox):
        while (item := inbox.get()) is not None:
            outbox.put(item)
    
    
    def ping(inbox, outbox, mine):
        while not stop:
            began = time.perf_counter()
            outbox.put(1)
            inbox.get()
            mine.append(time.perf_counter() - began)
        outbox.put(None)
    
    
    threads = []
    for mine in trips:
        there, back = queue.SimpleQueue(), queue.SimpleQueue()
        threads += [threading.Thread(target=echo, args=(there, back)), threading.Thread(target=ping, args=(back, there, mine))]
    for t in threads:
        t.start()
    time.sleep(seconds)
    stop = True
    for t in threads:
        t.join()
    every = sorted(x for mine in trips for x in mine)
    q = statistics.quantiles(every, n=1000, method="inclusive")
    print(f"p99.9 {q[998] * 1e3:.2f} ms, max {every[-1] * 1e3:.1f} ms")
    PYTHON_GIL=0 taskset -c 0,1,2 python3.15t simplequeue_pingpong.py 8 5
  4. henryiii commented on Nov 28, 2026

    @henryiii
    Contributor

    This is a bug I was investigating for pybind11. We had intermittent failures in CI that we thought were deadlocks on windows, and sticking AI on it found that that it was actually fixable by increasing our Windows timeout to 60 seconds (it was 10 seconds on all platforms). I tracked it to Cpython, I was able to make a pure Python reproducer (it's in pybind/pybind11#6294 if you'd like to see it). When looking into it, I found this issue; it seems to be the issue we were dealing with, and patch "D5" does help (only doing local timings on my Mac, though, only have easy access to Windows via CI currently).

    The fix belongs in CPython's _PyMutex_LockTimed (Python/lock.c), and there is already an open upstream issue with candidate patches: #162421. It has no PR and no core-dev reply yet.

    Here's the reproducer timings if that helps:

    Busy processes Measure Unpatched median / p99 D5 median / p99
    0 lock handoff 0.010 / 0.020 ms 0.010 / 0.033 ms
    0 Thread.start 0.016 / 0.049 ms 0.018 / 0.031 ms
    18 lock handoff 0.147 / 24 ms 0.006 / 0.27 ms
    18 Thread.start 0.141 / 25 ms 0.023 / 3.0 ms
    36 lock handoff 0.602 / 51 ms 0.006 / 0.03 ms
    36 Thread.start 0.411 / 47 ms 0.021 / 0.09 ms
  5. picnixz commented on Nov 28, 2026

    @picnixz
    Member

    Can we have an issue description that is not 3 km long or at least with <details> blocks because it's really hard to focus on what's wrong and what solutions are currently suggested.

    That being said, why can't we use exponential backoff here instead of a constant read every T ns? we might reduce the number of times we check (not sure if one of the patch suggested this; that's why I'd like to have a better issue description thatn just an LLM output that is really hard to parse)

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

    interpreter-coreperformancetopic-free-threadingtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions