How terminate Python thread without checking flag continuously

前端 未结 2 984
一向
一向 2020-12-19 14:45
class My_Thread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        print \"Starting \" + self.name
              


        
相关标签:
2条回答
  • 2020-12-19 14:51

    Python threads are not easy to kill, you can use the multiprocessing module (http://docs.python.org/2/library/multiprocessing.html) which is almost the same and it has terminate() function for killing a processes.

    Here is a little example, taken from the python docs.

    >>> import multiprocessing, time, signal
    >>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
    >>> print p, p.is_alive()
    <Process(Process-1, initial)> False
    >>> p.start()
    >>> print p, p.is_alive()
    <Process(Process-1, started)> True
    >>> p.terminate()
    >>> time.sleep(0.1)
    >>> print p, p.is_alive()
    <Process(Process-1, stopped[SIGTERM])> False
    >>> p.exitcode == -signal.SIGTERM
    True
    
    0 讨论(0)
  • 2020-12-19 14:57

    For your particular example, it's probably easiest to terminate the thread by terminating the subprocess it spawns using the Popen object's terminate() method...

    class My_Thread(threading.Thread):
    
        def __init__(self):
            threading.Thread.__init__(self)
            self.process = None
    
        def run(self):
            print "Starting " + self.name
            cmd = [ "bash", 'process.sh']
            self.process = p = subprocess.Popen(cmd,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
            for line in iter(p.stdout.readline, b''):
                print ("-- " + line.rstrip())
            print "Exiting " + self.name
    
        def stop(self):
            print "Trying to stop thread "
            if self.process is not None:
                self.process.terminate()
                self.process = None
    
    thr = My_Thread()
    thr.start()
    time.sleep(30)
    thr.stop()
    thr.join()
    

    ...causing a SIGTERM to be sent to bash, and the next call to p.stdout.readline() to raise an exception, which will terminate the thread.

    0 讨论(0)
提交回复
热议问题