Question on threads

Steve Holden steve at holdenweb.com
Fri Apr 11 17:47:59 EDT 2008


Jonathan Shao wrote:
> On Fri, Apr 11, 2008 at 3:29 PM, Steve Holden <steve at holdenweb.com 
> <mailto:steve at holdenweb.com>> wrote:
> 
>     Jonathan Shao wrote:
> 
>         Hi all,
>          I'm a beginner to Python, so please bear with me.
>          Is there a way of guarenteeing that all created threads in a
>         program are finished before the main program exits? I know that
>         using join() can guarentee this, but from the test scripts I've
>         run, it seems like join() also forces each individual thread to
>         terminate first before the next thread can finish. So if I
>         create like 20 threads in a for loop, and I join() each created
>         thread, then join() will in effect cause the threads to be
>         executed in serial rather than in parallel.
>          
> 
>     No it won't, as in fact there is no mechanism to force a thread to
>     terminate in Python. When you join() each created thread the main
>     thread will wait for each thread to finish. Supposing the
>     longest-lived thread finished first then all others will immediately
>     return from join().
> 
>     The only requirement it is imposing is that all sub-threads must be
>     finished before the main thread terminates.
> 
>     regards
>      Steve
>     -- 
>     Steve Holden        +1 571 484 6266   +1 800 494 3119
>     Holden Web LLC              http://www.holdenweb.com/
> 
>  
>  
> I guess I'm doing something wrong with join(). Here's a test script I 
> wrote up...
>  
> import threading
> import time
> class TestThread(threading.Thread):
>     def __init__(self, region):
>         self.region = region
>         threading.Thread.__init__(self)
>     def run(self):
>         for loop in range(10):
>             print "Region " + str(self.region) + " reporting: " + str(loop)
>             time.sleep(2)
> for x in range(10):
>     thr = TestThread(x)
>     thr.start()
>     thr.join()
> raw_input()
> In this script thread 0 will finish first... Am I doing something wrong 
> with join()?
>  
Yes - you are calling it before you have started ALL your threads, 
thereby making hte main thread wait for the end of thread 1 before 
starting the next. An impressive demonstration of thread 
synchronization, but not quite what you want :-)

Try saving the threads in a list then joining them later, like this 
(untested):

threads = []
for x in range(10):
    thr = TestThread(x)
    thr.start()
    threads.append(thr)
# Now all are started, wait for all to finish
for thr in threads:
    thr.join()

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/



More information about the Python-list mailing list