4

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?

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
pistacchio
  • 56,889
  • 107
  • 278
  • 420
  • duplicate to http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python – alf Jan 23 '12 at 15:00
  • 1
    oh, *another process...* Generally, process cannot get into other process's internals (unless of course it's not a `gdb`). I would either give up (preferred way), or use a debug interfaces. – alf Jan 23 '12 at 15:04
  • 6
    That's quite easy to do so long as you don't mind the entire process being killed at the same time. – David Heffernan Jan 23 '12 at 15:07
  • 2
    The usual way to deal with this problem is to use non-blocking I/O or a timeout. – Sven Marnach Jan 23 '12 at 15:08

1 Answers1

1

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()
ebarr
  • 7,704
  • 1
  • 29
  • 40