Python:如何终止多线程python程序?

时间:2017-06-15 12:58:40

标签: python multithreading terminate

我想创建一个程序,其中有两个主机列表可用。我想从每个主机读取数据。这将需要大约5-10秒,所以我想用不同的线程读取每个主机数据。

我创建了以下代码,它按照我的期望工作,但唯一的问题是当我按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后如何使程序终止。我错过了什么吗?

2 个答案:

答案 0 :(得分:0)

如果您只想让控件C完成所有操作,则无需在线程中使用停止功能。你可以对它们进行守护:

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添加到创建线程的代码中的所有其他位置。

哈努哈利

答案 1 :(得分:0)

你可以

  • 在主线程中捕获KeyboardInterrupt
  • 设置一个标志,以便其他线程可以检测到它并退出

  • catch KeyboardInterrupt
  • 调用os._exit()