Python:如何终止多线程的Python程序?
问题描述:
我想创建一个包含两个主机列表的程序。我想从每个主机读取数据。这将需要大约5-10秒,所以我想用不同的线程读取每个主机数据。Python:如何终止多线程的Python程序?
我创建了下面的代码,它按照我的期望工作,但问题是当我按下Ctrl + c时,程序没有终止。
我的代码:
import threading
import time,os,sys
import signal
is_running = True
def signal_handler(signal, frame):
print "cleaning up...please wait..."
v1.stop()
v2.stop()
global is_running
is_running = False
class Thread2(threading.Thread):
def __init__(self, function,args):
self.running = False
self.function = function
self.args = args
super(Thread2, self).__init__()
def start(self):
self.running = True
super(Thread2, self).start()
def run(self):
while is_running:
self.function(self.args)
time.sleep(time_interval)
def stop(self):
self.running = False
def b_iterate(hostnames):
for host_name in hostnames:
v = Thread2(function = read_cet_data,args = host_name)
v.start()
def read_b_data(host):
#
#reading some data from current host (5-10 seconds processing)
#
#here, this thread is not neccessary, want to stop or kill or terminate it
if threading.current_thread().isAlive():
threading.current_thread().stop()
def a_iterate(entp_hostnames):
for host_name in entp_hostnames:
v = Thread2(function = read_entp_data,args = host_name)
v.start()
def read_a_data(host):
#
#reading some data from current host (5-10 seconds processing)
#
#here, this thread is not neccessary, want to stop or kill or terminate it
if threading.current_thread().isAlive():
threading.current_thread().stop()
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal_handler)
#a_hostnmaes & b_hostnmaes are the lists of hostnames
v1 = Thread2(function = a_iterate,args = a_hostnames)
v2 = Thread2(function = b_iterate,args = b_hostnames)
v1.start()
v2.start()
while is_running:
pass
我怎样才能使按Ctrl + C后,这个程序终止。我错过了什么吗?
答
如果您只想控制C完成所有操作,则不需要在线程中使用停止功能。您可以将它们进行daemon:
v1 = Thread2(function = a_iterate,args = a_hostnames)
v2 = Thread2(function = b_iterate,args = b_hostnames)
v1.daemon = True
v2.daemon = True
v1.start()
v2.start()
只要主程序死掉,这些线程也会死机。您需要将.daemon = True添加到创建线程的代码中的所有其他位置。
哈努哈利
+0
@ Hannu-感谢您的答案。我有一个小小的怀疑。在read_b_data和read_a_data函数中,我如何终止或停止这个守护进程线程? – kit
答
您可以
- 抓一个KeyboardInterrupt在主线程
- 设置一个标志,以便另一个线程可以检测到它,并退出
或
- 赶上Keybo ardInterrupt
- 调用os._exit()
检查:https://*.com/questions/1112343/how-do-i-capture-sigint-in-python和https://计算器。 com/questions/18114560/python-catch-ctrl -c-command-prompt-really-want-to-quit-yn-resume-executi – Drako
@ Drako-我检查了它。由于多线程,我的程序没有终止。我如何通知它终止。 – kit
对不起,我从来没有需要任何多线程,只是轻量级的应用程序,在1线程运行良好:) - 没有经验,只是希望这些链接可以帮助想法 – Drako