views:

170

answers:

5

I am creating a thread in my Python app with thread.start_new_thread.

How do I stop it if it hasn't finished in three seconds time?

A: 

You cannot. Threads can't be killed from outside. The only thing you can do is add a way to ask the thread to exit. Obviously you won't be able to do this if the thread is blocked in some systemcall.

Thomas Wouters
A: 

You might be interested in this related question on StackOverflow.

Noctis Skytower
A: 

You can't do that directly. Anyway aborting a thread is not good practice - rather think about using synchronization mechanisms that let you abort the thread in a "soft" way.

But daemonic threads will automatically be aborted if no non-daemonic threads remain (e.g. if the only main thread ends). Maybe that's what you want.

AndiDog
+1  A: 

If you really need to do this (e.g. the thread calls code that may hang forever) then consider rewriting your code to spawn a process with the multiprocessing module. You can then kill the process with the Process.terminate() method. You will need 2.6 or later for this, of course.

Dave Kirby
A: 

As noted in a related question, you might be able to raise an exception through ctypes.pythonapi, but not while it's waiting on a system call.

eswald