Search code examples
pythonmultithreadingpython-multithreadingpysimplegui

Wait for threads to finish before creating a new thread


I have this small block of code where the goal is to basically wait for monitoring_function while it's still running.

monitoring_function = threading.Thread(target=start_monitoring, args=( cycles, window), daemon=True)
 if (monitoring_function.is_alive()):
   print("Still Running, Please wait!")
 else:
   print("Starting new Thread")
   monitoring_function.start()

But every time I try to run this code alongside my GUI, the code basically creates a new thread without ever hitting monitoring_function.is_alive() method. I have called on my method multiple times and it'll keep creating threads non-stop. Is it possible to run this sequentially, where it waits until the thread has been completed? I know one of the solutions is to use join() but using that method causes the entire PySimpleGUI to freeze and wait for the function to finish.


Solution

  • You always create a new thread before checking if necessary. Do this instead:

    # Execute following two lines only once
    
    monitoring_function = threading.Thread(target=start_monitoring, args=( cycles, window), daemon=True)
    monitoring_function.start()
    
    ... # Do other things
    
    # Check thread periodically like so:
    
    if monitoring_function.is_alive():
       print("Still Running, Please wait!")
    else:
       print("Starting new Thread")
       monitoring_function = threading.Thread(target=start_monitoring, args=( cycles, window), daemon=True)
       monitoring_function.start()