Question about thread

Jarek Zgoda jzgoda at gazeta.usun.pl
Fri Nov 19 15:56:30 EST 2004


Craig Ringer wrote:

>>When I do it line by line in python's console, I have similar result to youl.
>>But when I try to run it in a file, say:
>>
>>python demo.py
>>
>>It just returns me nothing. I have no idea on this right now...
> 
> You need to cause the main thread to wait on the child threads until
> they've all finished, otherwise - as Peter Hickman just mentioned - your
> script will terminate and all threads will end. Ten seconds on Google
> found this:
> 
> http://www.faqts.com/knowledge_base/view.phtml/aid/1364

Are you sure? I keep observing that child threads continue its execution 
until completion even if I do nothing in main thread. Consider this example:

import random, time
from threading import Thread

class Worker(Thread):

     def __init__(self, name):
         Thread.__init__(self)
         self.name = name
         print 'thread %s created' % self.name

     def run(self):
         amt = random.randint(1, 4)
         print 'thread %s waiting %d seconds' % (self.name, amt)
         time.sleep(amt)
         print 'thread %s finished' % self.name

     def __del__(self):
         print 'thread %s is being destroyed' % self.name

if __name__ == '__main__':
     for i in range(10):
         t = Worker('%.04d' % (i + 1, ))
         t.start()
     print 'finished creating threads'

Even after printing "finished creating threads" all spawned threads 
continue its execution up to final "thread nnnn is being destroyed", so 
I think there's no need to take any special action (unless it's Python 
on iSeries, buy this is another story) to wait for completion.

-- 
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/



More information about the Python-list mailing list