python - 键盘同时中断多个线程

标签 python multithreading keyboardinterrupt

我目前正在使用多个线程来收集数据并将其保存在 JSON 中。收集数据的循环是无限的。我希望能够使用 CTRL+C 结束所有线程。因此我创建了这个带有两个循环的简单版本。我尝试过不同的事情,但到目前为止还无法使其发挥作用。如何使用“except KeyboardInterrupt”同时停止两个循环?或者有更好的选择吗?

import threading
from time import sleep

number = 0 
numberino = 10

def background():
    while True:
        if number < 10:
            global number
            number=number+1
            print number
            sleep(1)
        else:
            print "10 seconds are over!"
            break

def foreground():
    while True:
        if numberino > -10:
            global numberino
            numberino=numberino-1
            print numberino
            sleep(1)
        else:
            print "20 seconds are over!"
            break


b = threading.Thread(name='background', target=background)
f = threading.Thread(name='foreground', target=foreground)

b.start()
f.start()

最佳答案

执行此操作的简单方法是让线程检查全局标志以查看是否到了退出的时间。一般原则是您不应该尝试终止线程,您应该要求它们退出,以便它们可以关闭它们可能打开的任何资源。

我修改了您的代码,以便线程(包括原始线程)检查全局 alive 标志。顺便说一句,您不应该将 global 指令放入循环内,并且它应该位于对要修改的全局变量的任何引用之前。最好的位置是把它放在函数的顶部。

import threading
from time import sleep

number = 0 
numberino = 10
alive = True

def background():
    global number
    while alive:
        if number < 10:
            number += 1
            print number
            sleep(1)
        else:
            print "10 seconds are over!"
            break

def foreground():
    global numberino
    while alive:
        if numberino > -10:
            numberino -= 1
            print numberino
            sleep(1)
        else:
            print "20 seconds are over!"
            break

b = threading.Thread(name='background', target=background)
f = threading.Thread(name='foreground', target=foreground)

b.start()
f.start()

while alive:
    try:
        sleep(.1)
    except KeyboardInterrupt:
        alive = False

print 'Bye'

关于python - 键盘同时中断多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50886731/

相关文章:

c++ - 将互斥锁引用从 main 传递到类

python - 在python中,调用后是否有可能发生异常,但其后的try block 为 "before"?

python - 安装 python 守护进程

python - Pandas:在 excel 文件中查找工作表列表

python - 如何让 postgresQL 在带有 django 的 Windows 7 计算机上工作?

java - 如何检查上下文是否仍然可以在android中使用?

c# - 创建表单并在后台线程上使用 Form.ShowDialog

python - 在没有 Django 其余部分的情况下使用 Django 模板和标签

python - 如何在使用 multiprocessing.Pool #python 时停止对 KeyboardInterrupt 的执行

driver - 键盘中断