python - 通过 CTRL+C 中断所有线程

标签 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)

最佳答案

您可以使用标志并让线程检查标志是否退出,而在主线程中,您应该捕获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/

相关文章:

python - 我可以在 conftest.py 中定义 fixture 以外的函数吗

c# - 使用任务返回值时出现 InvalidCastException

java - 等待然后接收文本字段输入而不卡住 GUI

python - 为什么我得到 "maximum recursion depth exceeded"

python - 折叠字符串中连续的字母数字字符

c# - Queue<T>.Dequeue 返回 null

c++ - 设计最快的页面下载

Python:我可以使用类变量作为线程锁吗?

php - 为什么 PHP7 在执行这个简单的循环时比 Python3 快这么多?

python - 我可以将 python 的 `for` 语句与这样的 SQL 结合起来吗 : `for id, name, ctime in db.select(' table_name', where ='...' )`