1

有没有办法用 Python 杀死一个特定的线程?我有一个线程运行一个循环函数,它干扰了程序的其他部分。当某个功能启动时我需要杀死它,有没有办法做到这一点?

4

2 回答 2

2

最好的方法是使用线程定期检查的退出标志,如果设置则退出。当您需要终止线程时,您将设置此标志并等待线程自行退出。

这个答案有关于为什么强行杀死线程是一个坏主意的附加信息,以及上述方法的 Python 实现。

于 2012-08-07T21:43:17.373 回答
0

我发现如果你用一个self.flag变量定义一个 Threading 类,并使你正在调用该类的函数的函数,那么你可以在一个线程特定的实例上设置标志并使用 if 语句退出特定的线程。

不难想象这更加动态并允许产生和关闭线程的能力。

class AutoPilotThreader(threading.Thread):
    def __init__(self, threadID, name):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.flag = 0
    def run(self):
      print "Starting " + self.name
      self.SelTestRun()
      print "Exiting " + self.name

    def SelTestRun(self):
        # do code
        while 1:
            if self.flag:
                return
            else:
                time.sleep(1)


my_threads = []
t1 = AutoPilotThreader(1, "t1")
t2 = AutoPilotThreader(2, "t2")
t1.start()
t2.start()
my_threads.append(t1)
my_threads.append(t2)


while 1:
    print("What would you like to do: 1. Quit 2. Start New 3. Check")
    choice = input("Enter : ")
    if choice == 1:
        choice = input(" 1 or 2 or 3 ")
        if choice == 1:
            t1.flag = 1
        elif choice ==2:
            t2.flag = 1
        elif choice ==3:
            t3.flag = 1  .........
于 2017-12-12T02:59:06.230 回答