thread vs threading -- Unexpected Results

Krzysztof Stachlewski stach at fr.pl
Thu Dec 4 07:36:07 EST 2003


"CK" <fw58959 at hotmail.com> wrote in message
news:c0367340.0312032212.70ab984a at posting.google.com...

> Program A - thread example
>
> #!/usr/local/bin/python
>
> import socket
> import time
> import thread
>
> def tcp_connect(dst_ip,dst_port):
>   print "%s Connecting to %s on port %d" %
> (time.asctime(),dst_ip,dst_port)
>   s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>   try:
>     s.connect((dst_ip,dst_port))
>   except:
>     pass
>   s.close()
>   print "%s Disconnecting from %s on port %d" %
> (time.asctime(),dst_ip,dst_port)
>
> for x in range(0,2):
>   for octet3 in range(32,36):
>       for octet4 in range(0,256):
>          ip_addr = "10.34."+str(octet3)+"."+str(octet4)
>          thread.start_new_thread(tcp_connect,(ip_addr,135))

After the loop completes, the main thread terminates
and so your whole program. You don't wait for the threads
to finish.

> Program B - threading example
> [...]
> for thread in threadlist:
>    thread.join()
>
> print "Main thread exitting"

And in this program you wait for the threads.

> Now in the threading example I have Connect / Disconnect pairs for the
> whole cycle.  I would have expected multiple Connects here and there
> and multiple Disconnects appearing here and there but it looks like
> at most only two threads are ever active (main + one).  Why don't
> I see multiple Connects / Disconnects??

In your threads' code you put the s.close() immediately after s.connect().
The connections are closed very quickly. This time is so short
that the scheduler did not switched tasks.
Why you see a different pattern of calls I cannot tell.
Probably an artefact of the task scheduler?
I would not worry about this. All of your
operations completed within one second.
Try to put something - at least a delay - between
connect() and close() and see how it works.

Stach





More information about the Python-list mailing list