HeitorLima HeitorLima - 2 years ago 134
Python Question

Python threading - do something while join()

Python 2.6.6

I hava a list of threads to be executed and the main code will wait (Threading.join()) until they're all finished.

>>> for thread in threadList:
... thread.start()
>>> for t in threadList:
... t.join()

Is there a way to print messages like "running..." while the main code waits the end of the threads?

I want to print the same thing ("running...") second after second until the threads are all done.



Implemented solution:

>>> for thread in threadList:
... thread.start()
>>> string = "running"
>>> while any(t.is_alive() for t in threadList):
... sys.stdout.write("\r%s" % string)
... sys.stdout.flush()
... string = string + "." #this may not be the best way
... time.sleep(0.5)

In my case, the extra time of "time.sleep(0.5)" is not an issue, although it's not the most recommended.

This generates the output:


The dots after "running" will be printed one after one, on the same line, while there is any thread alive. Exactly as I expected!

Based on the answers of @Manuel Jacob and @Alex Hall.

Answer Source

Thread.join() is blocking by design. Instead of using Thread.join(), you could periodically call Thread.is_alive().

Your example adapted:

for thread in threadList:
while any(thread.is_alive() for thread in threadList):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download