Restarting Demon threads in Python

Having just spent over an hour trying to find how to do this, here is my contribution to the problem.

Say that you have a thread that you have called start() on, and your run() method terminates with an exception, or quite naturally (for example, your listening to a socket, and it gets disconnected).

Your problem becomes that you now need to be able to re-call that thread to get it started again. However, progmatically, there’s no way of knowing if you have already called .start() on that thread. The thread is no-longer alive, so that doesn’t work. You get this (or similar) error:

raise RuntimeError(“threads can only be started once”)

The answer (at least so far) seems to be that you need to re-initialise the thread. By Placing:

threading.Thread.__init__(self)

At the end of your run() method, you can then call .start() on that thread again to your hearts content.

Now, I have no idea if this is good programming, or if there is a better way of getting this done, but it works for me, and my needs.

~BX


Posted

in

by

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.