Skip to content

Free-threading: signal.pthread_kill deadlocks child threads #150873

Open

Description

@crusaderky

Context

The Dask threaded scheduler (e.g. dask.array or dask.dataframe without dask.distributed) blocks the main thread when the user calls compute() and internally spawns a concurrent.futures.ThreadPoolExecutor to schedule tasks. If a user hits Ctrl+C, they expect the program to terminate soon (at most waiting for the tasks that are halfway through execution to terminate).

Bug report

This sequence frequently deadlocks on Linux x64 free-threaded:

  1. main thread calls threading.Thread.start
  2. another thread calls signal.pthread_kill(main_thread, signal.SIGINT), which lands after start() has returned but before the thread's target function has started executing
  3. main thread handles the resulting KeyboardInterrupt
  4. main thread calls .join() on the child thread started at point 1.
  5. frequently, .join() deadlocks. A second SIGINT (e.g. from Ctrl+C) unblocks it.

Reproducer

import signal
import threading

USE_BARRIER = False
NTHREADS = 20

def demo():
    main_thread = threading.get_ident()
    barrier = threading.Barrier(NTHREADS) if USE_BARRIER else None
    thread_can_die = threading.Event()

    def f() -> None:
        if barrier:
            barrier.wait()
        thread_can_die.wait()

    def interrupt() -> None:
        if barrier:
            barrier.wait()
        signal.pthread_kill(main_thread, signal.SIGINT)

    threads = []
    for _ in range(NTHREADS - 1):
        t = threading.Thread(target=f)
        t.start()
        threads.append(t)
    try:
        t = threading.Thread(target=interrupt)
        t.start()
        threads.append(t)
        for t in threads:
            t.join()
    except KeyboardInterrupt:
        pass
    else:
        assert False, "Expected KeyboardInterrupt"

    thread_can_die.set()
    for t in threads:
        t.join()


if __name__ == "__main__":
    i = 0
    while True:
        print(i, flush=True)
        demo()
        i += 1

On these setups, the above program hangs within a handful of cycles:

  • Linux x64 3.14.5t
  • Linux x64 git tip #7a468a101268d2b13105f94ae027df8b502d0c87 (built with Tools/pixi-packages/freethreading)

Cannot reproduce on

  • Linux x64 3.14.5

Setting USE_BARRIER=True, which ensures that all child threads are already fully started when the SIGINT lands on the main thread, makes the issue disappear.

CPython versions tested on:

CPython main branch, 3.14

Operating systems tested on:

Linux

Activity

  1. added
    type-bug
    on Jun 3, 2026
  2. picnixz commented on Jun 3, 2026

    @picnixz
    Member
  3. vstinner commented on Jun 4, 2026

    @vstinner
    Member

    It's not easy to make sure that the main thread is interrupted immediately (raise KeyboardInterrupt) when it receives a signal. It depends exactly when the signal is received.

    Call stack: t.join() => ThreadHandle_join() => PyEvent_WaitTimed() => _PyParkingLot_Park() => _PySemaphore_Wait() => sem_wait() (on Linux).

    When the signal is sent during sem_wait(), _PySemaphore_Wait() and _PyParkingLot_Park() return Py_PARK_INTR. If ThreadHandle_join() detects that PyEvent_WaitTimed() was interrupted, it calls Py_MakePendingCalls() which executes pending signal handlers. In this case, we are good, the code works as expected.

    The problem is when the signal is received by PyEvent_WaitTimed(), before sem_wait() call. In this case, sem_wait() hangs and is not interrupted, even if Python has a pending signal and we are in the main thread.

    _PyParkingLot_Park() can be called with no attached thread state, or it can detach the current thread state. So the Python C API cannot be used: PyErr_CheckSignals() cannot be called after the thread state is detached.

  4. vstinner commented on Jun 4, 2026

    @vstinner
    Member
  5. colesbury commented on Jun 4, 2026

    @colesbury
    Contributor

    Is this an issue primarily in Dask test code (as opposed to application code)?

    The underlying problem, which Victor described, is common to all Python versions. If the ctrl-c arrives in C code, but before sem_wait() (or other similar calls), then it won't interrupt the thread and you need to press ctrl-c again.

    The difference with free-threading is a matter of timing in the test code, but not in real applications. The GIL controls the synchronization of the signal.pthread_kill() with respect to the thread.join(), but it doesn't affect when a user presses ctrl-c or when the OS triggers the signal handling.

    I don't think this is something we can fix in CPython.

  6. crusaderky commented on Jun 4, 2026

    @crusaderky
    ContributorAuthor

    I think it's in application code.
    Here's a reproducer where the human has to actually hit Ctrl+C. I managed to get it hanging after 16 cycles on the first go and after 54 cycles on the second go. YMMV.

    The mitigation factor in real Dask use cases is that Dask keeps a warm global ThreadPoolExecutor, which is cleaned up by atexit.register(default_pool.shutdown). So this issue will manifest only if the user hits Ctrl+C when the executor needs an extra thread for the very first time since process start.

    import signal
    import threading
    
    NTHREADS = 20
    
    def demo():
        thread_can_die = threading.Event()
    
        def f() -> None:
            thread_can_die.wait()
    
        print("Hit Ctrl+C now and see if you can reach the next cycle", flush=True)
        threads = []
        while True:
            try:
                for _ in range(NTHREADS):
                    t = threading.Thread(target=f)
                    t.start()
                    threads.append(t)
                thread_can_die.set()
                for t in threads:
                    t.join()
                threads.clear()
            except KeyboardInterrupt:
                break
    
        thread_can_die.set()
        for t in threads:
            t.join()
    
    
    if __name__ == "__main__":
        i = 0
        while True:
            print(i, flush=True)
            demo()
            i += 1
  7. colesbury commented on Jun 4, 2026

    @colesbury
    Contributor

    I get the same behavior when running that in 3.14 and 3.14t. Most ctrl-c presses work every so often I get something like:

    Hit Ctrl+C now and see if you can reach the next cycle
    ^C^CTraceback (most recent call last):
      File "/home/sgross/issue150873/repro.py", line 36, in <module>
        demo()
        ~~~~^^
      File "/home/sgross/issue150873/repro.py", line 29, in demo
        t.join()
        ~~~~~~^^
      File "/home/sgross/.local/share/uv/python/cpython-3.14.3-linux-x86_64-gnu/lib/python3.14/threading.py", line 1133, in join
        self._os_thread_handle.join(timeout)
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^
    KeyboardInterrupt
    ^CException ignored while joining a thread in _thread._shutdown():
    Traceback (most recent call last):
      File "/home/sgross/.local/share/uv/python/cpython-3.14.3-linux-x86_64-gnu/lib/python3.14/threading.py", line 1583, in _shutdown
        _thread_shutdown()
    KeyboardInterrupt:
    sgross@nuc:~/issue150873$ ^C
    
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

    extension-modulestopic-free-threadingtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions