Starting threads

Peter Hansen peter at engcorp.com
Tue Jan 28 20:00:30 CET 2003


Lukas Kubin wrote:
> 
> I'm doing Python threads for the first time. In the following code I need
> to use the time.sleep(.005) for the thread to executed right. Otherwise it
> "omits" the first threads.
> The doTheAction() function is a socket operation which I need to connect
> parallelly to multimple computers. What am I doing wrong?

You're not doing anything _inherently_ wrong that would prevent this
from working, so it must be something related to the specifics of
Computers and doTheAction().  My guess is that doTheAction() is not
thread-safe and you are entering it multiple times without any kind of
"critical section" to protect the resources it uses.

> import threading
> 
> class Control(threading.Thread):
> 
>   def run(self):
>     doTheAction()
> 
> if __name__ == '__main__':
> 
>   for comp in Computers:
>     thread = Control()
>     thread.start()
>     time.sleep(.005)   # <-- This is what I still need to use

There are a few things you should tweak in any case.  Computers 
looks like a class name, because the convention is that names of
classes are capitalized in Python.  You might be going against this
convention, but it makes it harder for someone unfamiliar with
your code to read.

If you even plan on having your Control objects need any kind
of initialization, you should include an __init__ method that
calls the threading.Thread.__init__ method as well, since otherwise
your threads will not work properly.

Other than my guess above (and you'd have to tell more about what
doTheAction() does and how it does it), I can't see anything 
that is definitely the problem.

-Peter




More information about the Python-list mailing list