簡體   English   中英

Python:如何終止多線程python程序?

[英]Python: How to terminate multithreaded python program?

我想創建一個程序,其中有兩個主機列表可用。 我想從每個主機讀取數據。 這大約需要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后終止。 我想念什么嗎?

如果只希望控件C完成所有操作,則無需在線程中使用Stop函數。 您可以將它們守護進程:

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。

漢努

你可以

  • 在主線程中捕獲KeyboardInterrupt
  • 設置一個標志,以便另一個線程可以檢測到它並退出

要么

  • 抓住KeyboardInterrupt
  • 調用os._exit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM