python中具有kill函数的非块线程

时间:2017-08-08 08:07:08

标签: python multithreading

在Python编程中很常见,当我有一个函数或者什么时候我调用它会阻止我的代码继续进行。所以我认为解除阻塞的最佳方法是使用线程但是如果我需要停止线程我该怎么办? 我试过this reference并编写了这个简单的程序:

import threading
from time import sleep
class my_thread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(my_thread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        print("stopping the thread")
        self._stop_event.set()

    def stopped(self):
        value=self._stop_event.is_set()
        print("value of stop event is",value)
        return value
    def run(self):
        print("running the thread")
        print("start function startt()")
        self.startt()

    def startt(self):
        print("it is going to wait forever")
        while True:
            #wait forever
            pass
        print("This line never execute")


def main():
    for i in range(0,3):
        print("it is the main function")
        sleep(1)


if __name__+'__main__':
    thr=my_thread()
    thr.start()

    sleep(5)
    thr.stop()
    thr.stopped()
    print("calling the main function")
    main()
    print("Exiting the whole program")

我的问题是这个程序实际上是停止了线程但是在打印完最后一行后程序仍然运行。我想要的是如果我调用stop函数thr.start()它启动线程并运行#wait forever line并且如果我调用stop函数thr.stop()它会停止整个类并从{{1}返回到主要功能。

EDIT-- 作为@a_guest回答我可以解决它,但我的问题是一般的例如如果我有这个代码而不是#wait forever line

while True

(或任何其他代码)

我该怎么办?

2 个答案:

答案 0 :(得分:1)

而不是

while True:
    ...

你应该使用

while not self.stopped():
    ...

一旦你while线程,它就会突破stop()循环。

答案 1 :(得分:1)

你不能“中止”一个正在运行的线程,所以要停止它你必须在线程本身有一个机制,定期检查它是否应该停止。

常规线程继续运行,而其余程序(进程)退出。 但是,如果您将线程设置为“守护程序”线程,则在程序退出时它将自动被杀死。为此,请在线程的init方法中设置@Headers({ "Accept: application/json", "User-Agent: Your-App-Name", "Cache-Control: max-age=640000" }) 。更多信息https://docs.python.org/3/library/threading.html#threading.Thread.daemon