Skip to content

Instantly share code, notes, and snippets.

@kadaliao
Last active September 7, 2021 18:24
Show Gist options
  • Save kadaliao/297cf61012f727ec93f01eeafb135b32 to your computer and use it in GitHub Desktop.
Save kadaliao/297cf61012f727ec93f01eeafb135b32 to your computer and use it in GitHub Desktop.
使用事件优雅杀死 Python 线程
import threading
import time
import signal
# Python会等待非 daemon 线程运行结束,如果进程收到 SIGINT 信号,会提醒一次,第二次结束线程了
# Python不会等待 daemon 线程运行结束,收到 SIGINT 信号,就结束 Python 进程,线程也就不存在了
# 使用信号 handler 来优雅退出
event = threading.Event()
def bg():
for i in range(10):
print(f"{threading.current_thread().name}: {i}...")
if event.wait(1):
break
print(f"{i} iterations completed.")
def handler(signum, frame):
# print(f"{signum=}, {frame=}")
print("Received signal to interrupt")
event.set()
signal.signal(signal.SIGINT, handler)
th = threading.Thread(target=bg)
# th = threading.Thread(target=bg, daemon=True)
th.start()
th.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment