Memphis Bleek
Memphis Bleek

Reputation: 55

How to wait untill all threadings will be closed?

I use dynamic output in console and I have table with overall information about the dynamic data. With use threading like:

for i in list:
   th = threading.Thread(target=function_name, args=(i,))
   print(f'Thread named {th.getName()} is started')
   th.start()

A dynamic content in random parts of the table is present (it is no needed any dynamic content in table) I suppose, i must to wait until last th will be done, but how to do so? If I'll add string th.join() after th.start(), it will make no sense because I see, that it is no multithreading, but launched sequentially.

Upvotes: 1

Views: 45

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 99041

You can give a name to the thread and check if it's still active before continuing. Something like:

from time import sleep
import threading

for i in list:
   th = threading.Thread(target=function_name, args=(i), name="dload")
   print(f'Thread named {th.getName()} is started')
   th.start()
   while any(x.getName() for x in threading.enumerate() if "dload" == x.getName()):
       sleep(1) # or even a lower value: sleep(0.05)

Upvotes: 1

Emanuel
Emanuel

Reputation: 722

You need to create all the threads in list without starting them.

Then iterate over the list and start all the threads.

And eventually iterate again and join them all.

Another option is to use ThreadPoolExecutor

Upvotes: 0

Related Questions