Starting threads
James J. Besemer
jb at cascade-sys.com
Tue Jan 28 20:36:25 EST 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?
> Thank you.
>
>
> 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
>
Without the sleep (and even with it) your main thread can exit immediately
after starting the "Control" threads. This can be before the threads finish
and even before some or all of them actually really get started. THere may
be some implementations where the main thread waits for the other threads to
finish but on some implementations, exiting the main thread definitely kills
off the other threads whether they finish or not. So in general, you need
your main thread alive until all the sub-threads are done with their business.
One method to "run" N threads is to begin N-1 threads and use your main
thread to run the Nth thread.
It's a little cleaner to leave it as you have above and then have your main
thread execute signal.pause(). This causes the main thread to not compete
for cycles. HOwever, it resumes upon receipt of a signal.
In practice, your main thread likely will want to field some "signals". I
often employ something like the following:
Running = 1
def HandleSig( sig, frame ):
global Running
if sig == signal.SIGHUP: # maybe others
Running = 0
else:
print "Unk Sig"
def main():
signal.signal( signal.SIGHUP ) # maybe others
for comp in Computers:
thread = Control()
thread.start()
while Running:
signal.pause()
Regards
--jb
--
James J. Besemer 503-280-0838 voice
2727 NE Skidmore St. 503-280-0375 fax
Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com
http://cascade-sys.com
More information about the Python-list
mailing list