Reputation: 58863
I know that the proper way to kill a Thread subclass is to check periodically if some flag (like self.running
) is set to a certain "kill" value, but I have a Thread that may hang waiting for input and I'd like to kill it anyway from an external process.
Any help?
Upvotes: 4
Views: 1659
Reputation: 7842
If you are willing to switch from the threading module to the multiprocessing module for your thread interface, then this is possible. All that needs to be done, is to track the PID of each thread/process that is launched.
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()
Upvotes: 1