7

I'm writing a multi threaded Python app that makes many TCP connections to servers. Each connection is done on a separate thread. Sometimes the thread hangs for a long time which I don't want. How can I get the thread to kill itself after some given time period? From the main thread how can I determine that the child thread killed itself?

If possible I would appreciate a snippet of code showing how to do this. Thanks.

Update The system is Ubuntu 9:10

Simone
  • 11,655
  • 1
  • 30
  • 43
VacuumTube
  • 4,021
  • 4
  • 22
  • 19
  • What do you mean by hangs? If it's the network operation that hangs, can't you set a timeout for it? – Idan K Jan 25 '11 at 09:59
  • Yes I can set a network timeout, but that causes some other problems. See my question from yesterday. This method with no timeout works well for most hosts. I'd just like to know how to get a thread to kill itself. – VacuumTube Jan 25 '11 at 10:03
  • Read about threading.Timer "A thread that executes a function after a specified interval has passed." http://docs.python.org/library/threading.html#timer-objects . E.g. could you make a timer, call a function that closes the thread? – Daniel Farrell Jan 25 '11 at 10:31
  • 1
    Also the thread join method can be called with a timeout: join([timeout]), "When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof)", http://docs.python.org/library/threading.html#threading.Thread.join – Daniel Farrell Jan 25 '11 at 10:38
  • @VacuumTube are you working on UNIX-like system or Windows? – Simone Jan 25 '11 at 11:22
  • @Simone: Sorry I should have said. It's Ubuntu. I'll update the question. – VacuumTube Jan 25 '11 at 11:40
  • @VacuumTube I thought about your question a little, in the end I think you'd better find a different approach, such to avoid killing thread abruptly. This because killing thread in Python is not so easy (see http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) and because you'd expose your application to many pitfalls (resource not collected just to name one). – Simone Jan 25 '11 at 13:35

1 Answers1

5

Short answer: Just make the def run() end. So, if you are waiting for data from a socket, do it with timeout, then if timeout occur just break the while that you should have, and the thread will be killed.

You can check from main thread if a thread is alive with isAlive() method.

webbi
  • 841
  • 7
  • 14