Anyone who has used python before knows how painful threading can be. Especially if we have a multithreaded program that we require specific threads to "always" be alive.
Having hacked around for awhile I came up with the following solution:
import threading
import time
class ThreadRestartable(threading.Thread):
def __init__(self, theName):
threading.Thread.__init__(self, name=theName)
def run(self):
print "In ThreadRestartable\n"
time.sleep(10)
thd = ThreadRestartable("WORKER")
thd.start()
while(1):
i = 0
for t in threading.enumerate():
if t.name is "WORKER":
i = 1
print threading.enumerate()
if i == 0:
thd = ThreadRestartable("WORKER")
thd.start()
time.sleep(5)
We can see it running here:import time
class ThreadRestartable(threading.Thread):
def __init__(self, theName):
threading.Thread.__init__(self, name=theName)
def run(self):
print "In ThreadRestartable\n"
time.sleep(10)
thd = ThreadRestartable("WORKER")
thd.start()
while(1):
i = 0
for t in threading.enumerate():
if t.name is "WORKER":
i = 1
print threading.enumerate()
if i == 0:
thd = ThreadRestartable("WORKER")
thd.start()
time.sleep(5)
python run.py
In ThreadRestartable
[<_MainThread(MainThread, started 139833484474176)>,]
[<_MainThread(MainThread, started 139833484474176)>,]
[<_MainThread(MainThread, started 139833484474176)>,]
[<_MainThread(MainThread, started 139833484474176)>,]
[<_MainThread(MainThread, started 139833484474176)>,]
[<_MainThread(MainThread, started 139833484474176)>]
[<_MainThread(MainThread, started 139833484474176)>]
In ThreadRestartable
[<_MainThread(MainThread, started 139833484474176)>,]
[<_MainThread(MainThread, started 139833484474176)>,]
In ThreadRestartable
[<_MainThread(MainThread, started 139833484474176)>,
[<_MainThread(MainThread, started 139833484474176)>,
[<_MainThread(MainThread, started 139833484474176)>,
[<_MainThread(MainThread, started 139833484474176)>,
[<_MainThread(MainThread, started 139833484474176)>,
[<_MainThread(MainThread, started 139833484474176)>]
[<_MainThread(MainThread, started 139833484474176)>]
In ThreadRestartable
[<_MainThread(MainThread, started 139833484474176)>,
[<_MainThread(MainThread, started 139833484474176)>,
As we can see we use a named thread WORKER where we then use threading.enumerate() to look for the thread we named. If it does not exist we start it again. This would normally be used in a situation where we have a long running thread that should never end. In which case if you use the standard way of creating a thread then watch it with something like if not thread.IsAlive() and try to call start() on it again you will find python raises an assertion error. This is because the threading object needs to be recreated.
Hope this helps someone out there :)
No comments:
Post a Comment