2017-06-15 31 views
0

我想創建一個包含兩個主機列表的程序。我想從每個主機讀取數據。這將需要大約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後,這個程序終止。我錯過了什麼嗎?

+0

檢查:https://stackoverflow.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

+0

@ Drako-我檢查了它。由於多線程,我的程序沒有終止。我如何通知它終止。 – kit

+0

對不起,我從來沒有需要任何多線程,只是輕量級的應用程序,在1線程運行良好:) - 沒有經驗,只是希望這些鏈接可以幫助想法 – Drako

回答

0

如果您只想控制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

0

您可以

  • 抓一個KeyboardInterrupt在主線程
  • 設置一個標誌,以便另一個線程可以檢測到它,並退出

  • 趕上Keybo ardInterrupt
  • 調用os._exit()