0

I am working on some project where I have dependency from websocket data. And sometimes the sessions gets expired from the other side of the API. This is how how my thread is declared.

streaming_thread = threading.Thread(target=stream_live_load)
streaming_thread.start()

I just want to know how can I use the thread ID/Number to restart when the thread dies and restart the above again on loop until I kill it specifically.

martineau
  • 119,623
  • 25
  • 170
  • 301
Shivpe_R
  • 1,022
  • 2
  • 20
  • 31
  • Does this answer your question? [Is there any way to kill a Thread?](https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread) – Maurice Meyer Jun 22 '21 at 06:29
  • Threads have a `is_alive()` method you can used to determine if they are still running, so you could periodically check its status using that. – martineau Jun 22 '21 at 06:31
  • Why is the thread dying? If you can restart the websocket within the thread (handle the exception perhaps) then you will not need to restart the thread. Otherwise , you should look into thread pools. Python does not allow you to restart an exited thread, explicitly. – JimmyNJ Jul 02 '21 at 12:45

1 Answers1

1

Once a thread exits in Python you can not restart it. You will have to write code to check the status of the running thread and if it exits then re-initialize a new Thread object explicitly then, start the new instance.

You can, of course, write a container object to encapsulate this behavior.

    import threading
    from time import sleep

    def thread_worker(arg1, arg2, arg3):
        print("run({0},{1},{2})".format(arg1,arg2,arg3))
        sleep(5)
    
    while True:
        print("Restarting thread")
        th = threading.Thread( target = thread_worker, args = (2,3,4) )
        th.start()

        while th.is_alive():
            sleep(1)
JimmyNJ
  • 1,134
  • 1
  • 8
  • 23