键盘一次中断多个线程 [英] KeyboardInterrupt multiple threads at once

查看:105
本文介绍了键盘一次中断多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用多个线程来收集数据并将其保存为JSON.收集数据的循环是无限的.我希望能够使用CTRL + C结束所有线程.因此,我用两个循环创建了这个简单的版本.我已经尝试了不同的方法,但到目前为止还无法完成.如何使用"KeyboardInterrupt除外"立即停止两个循环?还是有更好的选择?

I am currently working with several threads to collect data and save it in a JSON. The loop to collect the data is infinite. I want to be able to end all the threads with CTRL+C. Therefore I created this simple version with two loops. I have tried different things, but can't make it work so far. How can I use "except KeyboardInterrupt" to stop both loops at once? Or is there a better option?

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()

推荐答案

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

The simple way to do this is to have your threads check a global flag to see if it's time to exit. The general principle is that you shouldn't try to kill threads, you should ask them to exit, so they can close any resources they may have open.

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

I've modified your code so that the threads (including the original thread) check the global alive flag. BTW, you shouldn't put a global directive inside a loop, and it should be before any reference to the global variable(s) you want to modify. The best place is to put it at the top of the function.

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'

这篇关于键盘一次中断多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆