2

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?

gmolau
  • 2,815
  • 1
  • 22
  • 45
  • Can you `join()` your threads? This will block until the thread has finished. – Hannu May 02 '18 at 13:46
  • @Hannu I could do this, but then I would have to keep a reference to that thread and pass it from the library through my client code to the main() function. That is why I was wondering if there is a way to 'discover' running daemon threads before exiting main() automatically. – gmolau May 02 '18 at 13:52
  • 2
    Loop over the results of `threading.enumerate()` and join the thread(s) you want ? – etene May 02 '18 at 14:04
  • 1
    @etene Oh, that's what I was looking for. Thank you! – gmolau May 02 '18 at 14:08
  • You're welcome. I can post that as a proper answer if you want. – etene May 02 '18 at 14:11
  • Sure, go ahead. – gmolau May 02 '18 at 14:13

1 Answers1

2

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.

etene
  • 710
  • 4
  • 12