[Tutor] Queued threads

Jeff Shannon jeffshannon at gmail.com
Wed Feb 16 21:49:38 CET 2005


On Wed, 16 Feb 2005 16:50:07 +1300, Liam Clarke <cyresse at gmail.com> wrote:
> Oops, you probably want to do this then-
> 
> for i in range( 0, 3 ):
>      oThread = Thread( target=mainFunction ).start()
> 
>     while oThread:
>              print 'sleeping 3 seconds'
>              time.sleep( 3 )

Probably not.  Note that, since oThread's value is not changed in the
body of this while loop, you will either never execute the body (if
oThread is false) or execute it infintely many times (if oThread is
true).  I doubt that's the desired behavior. ;)

In this case, since Thread.start() apparently always returns None, the
while loop is effectively a no-op.  However, if it *did* get
triggered, it would do so immediately after the first thread [which
returned a true value from start()] was started -- preventing later
threads from being started because the main program is stuck in this
endless loop.

You could perhaps rewrite the whole thing like this:

.for i in range(3):
.    mythread = Thread(target=mainFunction)
.    mythread.start()
.    while mythread.isAlive():
.        print "sleeping 3 seconds [main thread]"
.        time.sleep(3)

Though as others have said, if you're not starting the second thread
until the first is finished, then you might as well just make it
explicitly sequental and not bother with threads:

.for i in range(3):
.    mainFunction()

If you actually want the threads to process concurrently, and simply
wait until all of them are done, you could do this:

.threadlist = []
.for i in range (3):
.    mythread = Thread(target=mainFunction)
.    mythread.start()
.    threadlist.append(mythread)
.for thread in threadlist:
.    thread.join()

The join() method will wait until that thread is finished, and then
return.  If the thread is already finished when it's called, it
returns immediately.

Jeff Shannon


More information about the Tutor mailing list