Starting threads

Lukas Kubin kubin at opf.slu.cz
Wed Jan 29 02:51:13 EST 2003


Thank you for answer. OK, I will describe it better.
The doTheAction() function is defined in the Control class and looks
almost like this:

def sendSignal(address,port,command):
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  try:
    s.connect((address, port))
  except socket.error, msg:
    s = None
    return "false"
  s.send(command)
  # Here follows processing of returned values,etc.
  s.close()

The Control class is described in my previous letter bellow and the
Computer (it is not class I just badly shorted it for example) object is a
list of hostnames. So the main call looks like:

if __name__ == '__main__':

  for comp in ['hostname1','hostname2']:
    thread = Control(comp)
    thread.start()
    time.sleep(.005)

When I don't use the time.sleep() then it starts 2 threads of 'hostname2'.
Thank you

lukas

On Tue, 28 Jan 2003, Peter Hansen wrote:

> 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
>

-- 
Lukas Kubin

phone: +420696398285
email: kubin at opf.slu.cz

Information centre
The School of Business Administration in Karvina
Silesian University in Opava
Czech Republic
http://www.opf.slu.cz





More information about the Python-list mailing list