Last active
September 7, 2021 18:24
-
-
Save kadaliao/297cf61012f727ec93f01eeafb135b32 to your computer and use it in GitHub Desktop.
使用事件优雅杀死 Python 线程
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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