Python: How to determine when my thread becomes orphaned?

I have a program using a stream. When my program is closed, my thread is still running, and that's fine. I would like to know how my thread can detect that the main program has completed; ONLY ONLY. How can I do it?

My thread is in an infinite loop and processes many objects in the queue. I cannot define my thread as a daemon, otherwise I may lose some data at the end of the main program. I do not want my main program to set a boolean when closing.

+6
source share
2 answers

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 current live threads, and check if there is a main thread there.

Or, if this is not possible, you can check if the child thread is the only remaining non-daemon.

+4
source

Will it work if your manager keeps track of how many open threads were there, then the children killed themselves when they were starving for entry? Thus, the parent will begin to push the data into the queue, and workers will consume the data from the queue. If the employee did not find anything in the queue for a certain timeout period, he will kill himself. Then the main thread will track how many workers are working, and periodically start new workers if the number of active workers is under a given threshold.

0
source

Source: https://habr.com/ru/post/921686/


All Articles