How terminate Python thread without checking flag continuously

前端 未结 2 995
一向
一向 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()
     False
    >>> p.start()
    >>> print p, p.is_alive()
     True
    >>> p.terminate()
    >>> time.sleep(0.1)
    >>> print p, p.is_alive()
     False
    >>> p.exitcode == -signal.SIGTERM
    True
    

提交回复
热议问题