[Tutor] Waiting until a thread ends
lists at justuber.com
Fri Mar 18 01:00:44 CET 2011
> Only really glanced at this, but you seem to be checking only the last
>> thread *after* the loop? Surely you should be storing all the threads in a
>> list (or someplace) as you create them, and then check them all for liveness
>> and if so join them each in turn, to ensure you only print 'FINISHED' once
>> you've checked and confirmed that all the threads created have in fact
> That makes absolute sense. Doh on my part!
Just done a little more reading and came across this in an O'Reilly article
Seems like an elegant way to accomplish a wait until all running threads
Using enumerate() to wait for all running threads:
It is not necessary to retain an explicit handle to all of the daemon
threads you start in order to ensure they have completed before exiting the
main process. threading.enumerate()returns a list of active Thread instances.
The list includes the current thread, and since joining the current thread
is not allowed (it introduces a deadlock situation), we must check before
import randomimport threadingimport time
"""thread worker function"""
t = threading.currentThread()
pause = random.randint(1,5)
print 'Starting:', t.getName(), 'sleeping', pause
print 'Ending :', t.getName()
for i in range(3):
t = threading.Thread(target=worker)
main_thread = threading.currentThread()for t in threading.enumerate():
if t is main_thread:
print 'Joining :', t.getName()
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor