Need help with threads

Jeff Shannon jeff at
Wed Jun 13 17:30:41 EDT 2001

Damian Menscher <menscher+python at> wrote in message news:<_nOV6.9330$ki5.130125 at>...
> I'm trying to use threads to run various processes that require some
> I/O.  This is apparently broken.  Here's a simple program:
> =================================================
> #!/usr/bin/python
> import time
> import thread
> import popen2


> While I'm posting... is there an elegant way to wait till all threads
> have finished?  I can't count on things finishing in a fixed time for
> my application.
> Ideas?  Please??
> Damian Menscher

My suggestion would be to use the 'threading' module instead of the 'thread'
module--it's a higher level, cleaner interface.

import threading

def ThreadFunc(my_arg):
    print "Thread given argument of: %s" % str(my_arg)

for n in range(10):
    threadname = "MyThread%d" % n
    newthread = threading.Thread( target=ThreadFunc, name=threadname, args=(n,) )

the threading module defines a Thread class whose constructor takes several
keyword arguments, some of which are optional.  Most important is the target 
argument, which is the function that comprises the body of the thread.  This
function is passed a tuple of arguments specified by args.  Check the 
docstrings and help file of the threading module for more details.

Also, if you wish to pause until a particular thread is finished, you can
use the Thread.join() method, which also has an optional timeout parameter--
i.e., mythread.join(30) will pause until mythread finishes execution or 30
seconds have passed, whichever comes first, thus allowing you to have a chance
to kill or recover from a deadlocked thread.  (Timeouts are a good thing.)

p.s. I suspect that your problem may have been due to some subtle deadlock
or race condition between your threads, though I'm not sure.  Any time any
thread accesses a global resource, it should be protected by some sort of 
lock or semaphore.  Technically, this probably applies even to the print
statement in my example, but.....   :)

Jeff Shannon
Credit International

More information about the Python-list mailing list