我目前正在使用多个线程来收集数据并将其保存在 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/