2012-01-23 161 views
4

我知道殺死線程子類的正確方法是定期檢查某個標記(如self.running)是否設置爲某個「kill」值,但我有一個可能會掛起的線程等待輸入,我想從外部進程中殺死它。殺死另一個進程的線程

任何幫助?

+0

式兩份,http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python – alf

+1

哦,*另一個進程... *一般,進程無法進入其他進程的內部(除非它當然不是'gdb')。我要麼放棄(首選方式),要麼使用調試接口。 – alf

+6

只要你不介意整個過程在同一時間被殺死,這很容易做到。 –

回答

1

如果您願意從線程模塊切換到您的線程接口的多處理模塊,那麼這是可能的。所有需要完成的工作是跟蹤每個啓動的線程/進程的PID。

from multiprocessing import Process 
    import os,time 

    class myThread(Process): 
     def __init__(self): 
      Process.__init__(self) 

     def run(self): 
      while True: 
       os.system("sleep 5") 


    if __name__ == '__main__': 
     p = myThread() 
     p.start() 
     print "Main thread PID:",os.getpid() 
     print "Launched process PID:",p.pid 
     os.kill(p.pid,1) 
     p.join()