0

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?

CroatiaHR
  • 615
  • 6
  • 24

1 Answers1

0

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(not thread.is_alive() for thread in thread_list)
while not finished:
    finished = all(not thread.is_alive() for thread in thread_list)
print('All task finished...')
Community
  • 1
  • 1
devaerial
  • 2,069
  • 3
  • 19
  • 33
  • do you think a sleep() command will interfere with the threads ? I wouldnt want it to keep asking if they are done, it should go on a interval.. – CroatiaHR Jul 03 '19 at 14:06
  • 1
    you can use `time.sleep` although I'm not entirely sure how your program will behave. Python itself does not support `parallelism`. In reality only one thread is executed at the time. From [this](https://stackoverflow.com/questions/92928/time-sleep-sleeps-thread-or-process) SO thread it seems like it should not be a problem. – devaerial Jul 03 '19 at 14:11