当前位置: 动力学知识库 > 问答 > 编程问答 >

multithreading - Killing thread in python

问题描述:

I defined class A which has a method like this.

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)

If I define an instance of a this class in another script and run func method of this instance, how can I break while loop and stop these threads correctly? Do I need a ctrl-c signal handler in class A, if yes how? Note: I am also calling a system call by os.system function in func2 method of class A. Problem is when I run main script file and try to stop running of these threads, they do not stop.

网友答案:

There are myriads of ways to achieve what you want, one of the most straightforward ones would be using 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

Meanwhile in some other thread (assuming the object your're talking about is obj):

obj.stop_event.set()

to finish the loop in the next iteration.

分享给朋友:
您可能感兴趣的文章:
随机阅读: