Question

I have a program using a thread. When my program is closed, my thread is still running and that's normal. I would like to know how my thread can detect that the main program is terminated; by itself ONLY. How would I do that?

My thread is in an infinite loop and process many object in a Queue. I can't define my thread as a daemon, else I can lose some data at the end of the main program. I don't want that my main program set a boolean value when it closed.

Was it helpful?

Solution

If you can get a handle to the main thread, you can call is_alive() on it.

Alternatively, you can call threading.enumerate() to get a list of all currently living threads, and check to see if the main thread is in there.

Or if even that is impossible, then you might be able to check to see if the child thread is the only remaining non-daemon thread.

OTHER TIPS

Would it work if your manager tracked how many open threads there were, then the children killed themselves when starved of input? So the parent would start pushing data on to the queue, and the workers would consume data from the queue. If a worker found nothing on the queue for a certain timeout period, it would kill itself. The main thread would then track how many workers were operating and periodically start new workers if the number of active workers were under a given threshold.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top