Skip to content

STW waits when a thread detaches without suspending #162764

Backlog

Description

@nascheme

Bug report

In the free-threaded build, stop_the_world() waits for other threads with PyEvent_WaitTimed(&stw->stop_event, 1ms) and re-polls park_detached_threads() when the timeout expires. The event is only signalled by decrement_stoptheworld_countdown(), which is called when a thread suspends itself via _PyThreadState_Suspend() (eval breaker path) or when the requester parks a detached thread.

A thread that is attached when the stop is requested, but then detaches through _PyThreadState_Detach() instead of checking the eval breaker, never signals the event. Examples:

The requester then sleeps until the 1 ms timeout, even though the thread it waits for became detached almost immediately. During that time no thread makes progress: the requester holds the stop-the-world mutex, the other threads are suspended, and the straggler is usually blocked on a lock held by the requester. So each affected pause costs about 1 ms.

This was found while investigating gh-162752. The type slot update fix for that issue avoids stopping the world when no slot changes. Slot updates that do change something still hit the 1 ms delay under contention, and the problem is not specific to type slots: any stop-the-world requester (GC, type updates, etc.) can hit it.

Reproducer

import sys, threading, time
import _testinternalcapi

MODE = sys.argv[1] if len(sys.argv) > 1 else "sleep"
N = 1000
stop = False

def spin():
    # Pure Python loop: notices the stop request via the eval breaker.
    while not stop:
        pass

def sleep():
    # time.sleep(0) detaches with Py_BEGIN_ALLOW_THREADS.
    while not stop:
        time.sleep(0)

lock = threading.Lock()
def lock_contend():
    # Two threads contend on a lock; the waiter detaches while parked.
    while not stop:
        with lock:
            pass

workers = {"none": [], "spin": [spin], "sleep": [sleep],
           "lock": [lock_contend, lock_contend]}[MODE]
threads = [threading.Thread(target=w) for w in workers]
for t in threads:
    t.start()
time.sleep(0.1)
t0 = time.perf_counter()
for _ in range(N):
    _testinternalcapi.stop_the_world()
dt = time.perf_counter() - t0
stop = True
for t in threads:
    t.join()
print(f"{MODE:6}: {dt / N * 1e6:7.1f} us per stop-the-world")

Free-threaded debug build, Linux x86-64, us per stop-the-world:

Mode main poll interval reduced to 10 us
none 0.3 0.3
spin 131 64
sleep 39 1.5
lock 677 67

In the sleep and lock modes the worker threads keep detaching through _PyThreadState_Detach(), so a stop that is requested while a worker is attached is only completed by the poll.

The same thing happens with type slot updates (gh-162752), which stop the world while holding TYPE_LOCK: a second thread contending for TYPE_LOCK is attached when the stop is requested, then blocks on TYPE_LOCK and detaches without signalling. gdb shows one thread in stop_the_world -> PyEvent_WaitTimed and the other parked in _PyCriticalSection2_BeginSlow. A loop doing C.__getitem__ = f; del C.__getitem__ in each of 2 threads takes about 660 us per slot update, versus 1.3 us with 1 thread.

Experiments on that case (2 threads, C.__getitem__ = lambda ... benchmark from gh-162752, release build):

Change us per assignment
main 429
poll interval reduced to 10 us 2.2
_PyThreadState_Detach() calls _PyThreadState_Suspend() 3.9

The last change is not a proposed fix, since it takes HEAD_LOCK on every detach.

Possible fix

When detaching, check whether a stop-the-world is pending and, if so, signal the requester:

  • After detach_thread() stores _Py_THREAD_DETACHED, load stoptheworld.requested (runtime and interpreter). This is a single atomic load in the common case.
  • If a stop is pending, take HEAD_LOCK, CAS the thread state from DETACHED to SUSPENDED, and if that succeeds call decrement_stoptheworld_countdown(). If the CAS fails, the requester already parked the thread in park_detached_threads(), so nothing is counted twice.
  • stw->requested is currently a plain store under HEAD_LOCK and would need to be written atomically so that either the requester sees the detached state or the detaching thread sees the request.

The 1 ms poll could stay as a fallback.

A simpler alternative is an adaptive poll (start at a few us and back off to 1 ms), but that only reduces the delay and still costs CPU in the requester.

Note that the 1 ms timeout does not act as backoff between stop-the-world pauses: it only delays a pause that is already in progress, while every thread except the straggler is already stopped. If rate limiting of frequent pauses is needed, it should be a separate mechanism between pauses.

Note: investigation and write-up of this bug report was assisted by an LLM agent.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. self-assigned this
    on Nov 27, 2026
  2. added
    type-bug
    performance
    on Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

performancetopic-free-threadingtype-bug

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions