python / python/cpython

Free-threading: `signal.pthread_kill` deadlocks child threads

Abierto
#150,873 6 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

extension-modules topic-free-threading type-bug
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

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

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Empieza ejecutando el reproducer proporcionado en Linux x64 free-threaded CPython y, a continuación, sigue la interacción entre threading.Thread.start(), threading.Thread.join() y signal.pthread_kill(). Se considera terminado cuando el reproducer deja de quedar bloqueado si SIGINT llega antes de que comience el target de un hilo hijo, y el comportamiento esperado de KeyboardInterrupt permanece intacto.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
operating-systems
Tipo de issue
Error
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Tranquilo
Claridad
Bastante claro
Aptitud para principiantes
45/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.