1

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?

Fahad Sadah
  • 2,368
  • 3
  • 18
  • 27
  • If you are downloading data, you can set a socket timeout. – wisty Feb 09 '10 at 05:30
  • You might be interested in this [related question](http://stackoverflow.com/questions/2196999/how-to-add-a-timeout-to-a-function-in-python-cross-platform) on StackOverflow. – Noctis Skytower Feb 08 '10 at 17:56

4 Answers4

2

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
  • 68,631
  • 21
  • 159
  • 205
1

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
  • 130,178
  • 23
  • 148
  • 122
1

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
  • 25,806
  • 5
  • 67
  • 84
1

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.

Community
  • 1
  • 1
eswald
  • 8,368
  • 4
  • 28
  • 28