10

I have been looking all over the place for a good timeout script that can kill a thread if it's been active for more than X seconds, but all the examples I've seen have flaws that don't always stop the thread. Using thread.join(x) ends up defeating the purpose of it being a thread.

The only decent example I have found is Timeout on a function call and that one is not without its flaws..

Anyone know of a better way to do this?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Ian
  • 24,116
  • 22
  • 58
  • 96
  • The Python folks made this hard on purpose because usually it's a bad idea to kill something that might be writing to shared memory. Could you use a process instead of a thread? – Dave May 01 '09 at 15:06
  • Well, in this case it's for a mod_wsgi script, so it's more of a termination thing. Once the script runs over the time limit, just kill the whole thread and exit, so potentially damaging shared memory isn't such a big problem. – Ian May 01 '09 at 15:24
  • Are you running in daemon mode or embedded mode? – Dave May 01 '09 at 15:36
  • it is a pain that there is no easy way to kill a thread, the thread could be a hanged up HTTP connection, due to DNS lookup etc. – Asiel Diaz Benitez Jun 08 '21 at 17:29

2 Answers2

2

See my answer to python: how to send packets in multi thread and then the thread kill itself - there is a fragment with InterruptableThread class and example that kill another thread after timeout - exactly what you want.

There is also similar Python recipe at activestate.

Community
  • 1
  • 1
Jiri
  • 16,425
  • 6
  • 52
  • 68
0

I know this might not be what you want, but have you considered the signal approach? Timeout on a function call http://docs.python.org/library/signal.html#example

You can set an alarm signal at the beginning of the thread execution, and then stop the thread in the signal handler.

Community
  • 1
  • 1
Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152