Warm tip: This article is reproduced from stackoverflow.com, please click
python-3.x

How to check if all opened threading processes are finished?

发布于 2020-03-27 10:15:06

I wanted to implement some threading in my code, and it seemed at first that it was working fine. After checking my results, I have noticed that the code seems not to wait for the threads to be finished, but instead as long as they start, it continues with the rest of the code.

    def start_local_process(pair):
        try:
            name = 'name'
            some_other_function(name)
        except:
            print("Failed")

    print("Starting a total of %d threading processes." %len(some_list))
    for element in some_list:
        t= Thread(target=start_local_process, args=(pair,))
        t.start()
    print("Closed all threading processes for " + element + "!")

I can see that it does start a thread process for each element in some_list, which exactly what I want -parallel execution for each element. But, I get the last output message immediately after starting them, what I would prefer is, if it would wait for them to finish and then so print a message that they are finished. Is there a way to do it ?

UPDATE: So, here is a link where part of the solution was given. The function that answers if a thread is still active is .isAlive()

With this function I could know if a thread is still active or not, but what would be a neat way of rechecking the same thing until all of the functions return TRUE?

Questioner
CroatiaHR
Viewed
126
devaerial 2019-07-03 21:12

Supposing you're saving your threads to list, you can do the following thing to check if all your threads finished the work:

finished = all(thread.isAlive() for thread in thread_list)
while not finished:
    finished = all(thread.isAlive() for thread in thread_list)
print('All task finished...')