繁体   English   中英

杀死Python中的线程

[英]Killing thread in python

我定义了类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信号处理程序? 注意:我也在类A的func2方法中通过os.system函数调用系统调用。问题是当我运行主脚本文件并尝试停止运行这些线程时,它们不会停止。

有多种方法可以实现您想要的目标,最直接的方法之一就是使用事件

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()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM