NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Middle82 views

Можно ли в Python безопасно принудительно завершить выполняющийся поток?

Practice

AI answer

No, there is no safe way to forcibly stop a standard Python thread from the outside. A thread may hold locks or be inside a critical section; forcibly terminating it can leave data and program state inconsistent.

A cooperative stop is usually used instead: the thread periodically checks a threading.Event and exits on its own.

import threading

stop = threading.Event()

def worker():
    while not stop.is_set():
        do_one_unit_of_work()

thread = threading.Thread(target=worker)
thread.start()

stop.set()
thread.join()

Long-running blocking I/O operations should have timeouts or be interrupted using the API provided for that purpose. If you need to stop computations forcefully, it is better to run them in a separate process: a process can be terminated, though you still need to account for resource cleanup and the consistency of external data.