当我按 CTRL+C 中断程序时,它仅退出主线程,而新创建的线程仍在工作。如何终止所有线程?
import threading, time
def loop():
while True:
print("maked thread")
time.sleep(1)
t = threading.Thread(target = loop)
t.start()
while True:
print("loop")
time.sleep(1)
最佳答案
您可以使用标志并让线程检查标志是否退出,而在主线程中,您应该捕获KeyboardInterrupt
异常并设置标志。
import threading, time
import sys
stop = False
def loop():
while not stop:
print("maked thread")
time.sleep(1)
print('exiting thread')
t = threading.Thread(target = loop)
t.start()
try:
while True:
print("loop")
time.sleep(1)
except KeyboardInterrupt:
stop = True
sys.exit()
关于python - 通过 CTRL+C 中断所有线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51609438/