通过CTRL + C中断所有线程

时间:2018-07-31 09:00:07

标签: python multithreading

当我按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)

1 个答案:

答案 0 :(得分:2)

您可以使用use标志并使线程检查退出标志,而在主线程中应捕获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()