Search code examples
pythonmultithreadingpython-multithreadinggoogle-cloud-python

Simple way to wait for all deamon threads to finish before exiting a Python program?


I have a long running operation that is monitored from a daemon thread and invokes a callback in the main thread once it is finished.

Python programs exit when only daemon threads are left. This is a bit unfortunate in my situation, because it means that the callback will never be called if the program exits before the long running operation finishes.

The callback scheduling and monitoring happens deep inside an external library, so I can't easily modify it (the long running operation is a google.api_core.operation.Operation).

Is there is a simple way to wait for this daemon thread to finish from my client code? Or another way to ensure that the callback will run?


Solution

  • If you want to wait for daemon threads to exit before the main program exits, but for some reason you don't have a reference to these threads, the threading module has you covered:

    It provides an enumerate function that returns a list of currently active threads. Just loop over its results and join() the threads you're interested in.