在python中杀死线程

时间:2013-10-23 07:37:14

标签: python multithreading

我定义了A类,它有这样的方法。

def func(self):
    while True:
        threading.Timer(0,self.func2, ["0"]).start()
        time.sleep(nseconds)
        threading.Timer(0,self.func2, ["1"]).start()
        time.sleep(nseconds)  

如果我在另一个脚本中定义此类的实例并运行此实例的func方法,那么如何在while循环中断开并正确停止这些线程?我是否需要A类中的ctrl-c信号处理程序,如果是,如何?注意:我也在类{的os.system方法中通过func2函数调用系统调用。问题是当我运行主脚本文件并尝试停止运行这些线程时,它们不会停止。 / p>

1 个答案:

答案 0 :(得分:3)

有无数种方法可以达到你想要的效果,其中一种最直接的方法是使用Events

from threading import Event

class Foo(object):

    def __init__(self):
        # the stop event is initially set to false, use .set() to set it true
        self.stop_event = Event()

    def func(self):
        while not self.stop_event.is_set():
           # your code

同时在其他一些帖子中(假设你所谈论的对象是obj):

obj.stop_event.set()

在下一次迭代中完成循环。