Python,停止线程

时间:2017-12-07 13:17:06

标签: python multithreading kill

我试图创建一个ping IP地址并保留连接/未连接时间记录的类。

由于此类是GUI的一部分,我希望在用户询问时停止此线程。

发现一些Q& As重新解决了这个问题,但实际上没有一个导致线程停止。

我试图制作一个方法,这个课程的一部分将停止self.run()

这是我的Pinger课程:

class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4

    def run(self):
            self.start_ping()

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while True:
            ping_result = os.system('ping %s -n 1 >Null' % self.address)
            self.ping_vector.append(ping_result)

            if self.last_ping != ping_result:
                text = ['Reachable', 'Lost']
                print(str(self.timestamp)[:-4], self.address, text[ping_result])

            round_time_qouta = datetime.datetime.now() - self.timestamp
            self.timestamp = datetime.datetime.now()
            self.update_time_counter(ping_result, round_time_qouta)

            self.last_ping = ping_result
            time.sleep(self.ping_rate)

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]

4 个答案:

答案 0 :(得分:1)

使用_Thread_stop():

MyPinger._Thread__stop()

答案 1 :(得分:1)

我会以不同的方式对你的类进行编码,以作为守护进程运行。

将start_ping代码保留并使用下一个代码:

MyPinger = threading.Thread(target = self.start_ping, name="Pinger")
MyPinger.setDaemon(True)
MyPinger.start() # launch start_ping

并且可以使用_Thread_stop()来阻止它,这有点粗野......:

if MyPinger.IsAlive():
   MyPinger._Thread__stop() 

答案 2 :(得分:1)

正如我在评论中所说,最简单的方法是使用threading.Event在线程退出时发出信号。这样你可以公开事件并让其他线程设置它,同时你可以从你的线程中检查它的状态并在请求时退出。

在您的情况下,它可以像下面这样简单:

class Pinger(threading.Thread):

    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)
        self.kill = threading.Event()
        # the rest of your setup...

    # etc.

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while not self.kill.is_set():
            # do your pinging stuff

    # etc.

然后,只要您希望线程停止(例如从您的用户界面),只需调用它:pinger_instance.kill.set()即可完成。请注意,由于阻止os.system()调用以及time.sleep()方法结束时的Pinger.start_ping()而导致它被杀死需要一些时间。

答案 3 :(得分:1)

感谢@zwer领先。 这是我的完整代码(标记了更改)

class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4
        self.event = threading.Event() # <---- Added

    def run(self):
        while not self.event.is_set(): # <---- Added
            self.start_ping()
            self.event.wait(self.ping_rate) # <---- Added ( Time to repeat moved in here )

    def stop(self):       # <---- Added ( ease of use )
        self.event.set()  # <---- Added ( set to False and causes to stop )


    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        # While loop ##--- > Deleted. now it loops in run method #####
        ping_result = os.system('ping %s -n 1 >Null' % self.address)
        self.ping_vector.append(ping_result)

        if self.last_ping != ping_result:
            text = ['Reachable', 'Lost']
            print(str(self.timestamp)[:-4], self.address, text[ping_result])

        round_time_qouta = datetime.datetime.now() - self.timestamp
        self.timestamp = datetime.datetime.now()
        self.update_time_counter(ping_result, round_time_qouta)

        self.last_ping = ping_result
        #### time.sleep (self.ping_rate)  # <---- deleted 

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]

    def get_status(self):
        return self.last_status


c = Pinger('127.0.0.1', 5)
c.start()
time.sleep(10)
c.stop()