Created
April 2, 2019 18:06
-
-
Save luiscoms/afa828af2b40e6eeb1682eaa734963c1 to your computer and use it in GitHub Desktop.
RestartableThread from python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from threading import Thread | |
class RestartableThread(Thread): | |
def __init__(self, *args, **kwargs): | |
self.init_args, self.init_kwargs = args, kwargs | |
super(RestartableThread, self).__init__(*args, **kwargs) | |
def clone(self): | |
r = RestartableThread(*self.init_args, **self.init_kwargs) | |
r.start() | |
return r | |
if __name__ == '__main__': | |
threads = [] | |
t = RestartableThread(target=print, args=("I am alive!",)) | |
t.start() | |
threads.append(t) | |
while True: | |
for m in threads[:]: | |
if not m.isAlive(): | |
print("Thread is not alive, restarting %s", t.getName()) | |
threads.remove(m) | |
threads.append(m.clone()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment