Speed up with threads

Rhymes raims at dot.com
Sun Aug 4 21:45:02 CEST 2002


On Sun, 04 Aug 2002 12:23:50 GMT, Syver Enstad
<syver-en+usenet at online.no> wrote:

>You'll have to make the two classes share the same Queue, maybe like
>this:
>
>In the ctor for the main class, or an init method of some kind:
>self._queue = Queue.Queue()
>
>in a loop creating the Scanners:
>self._scanners.append(Scanner(self._queue))

I don't understand how link scanners (the list) with the queue...

this is my whole unstable code (the queue version):

import socket as sk
import sys
import threading, Queue

#MAX_THREADS = 50
queue = Queue.Queue()
scanners = []

def usage():
    print "\npyScan 0.1a - Rhymes (rhymes at myself.com)"
    print "usage: pyScan <host> [start port] [end port]"

class Scanner(threading.Thread):
##    def __init__(self, host, port):
    def __init__(self):     
        threading.Thread.__init__(self)
##        # host and port
##        self.host = host
##        self.port = port
        # build up the socket obj
        self.sd = sk.socket(sk.AF_INET, sk.SOCK_STREAM)

    def run(self):
        try:
            host, port = queue.get()
            # connect to the given host:port
            self.sd.connect((host, port))
            print "%s:%d OPEN" % (host, port)
            self.sd.close()
        except: pass

class pyScan:
    def __init__(self, args=[]):
        self.args = args
        self.start, self.stop = 1, 1024
        self.host = ""       

        # check the arguments
        if len(self.args) == 4:
            self.host = self.args[1]
            try:
                self.start = int(self.args[2])
                self.stop = int(self.args[3])
            except ValueError:
                usage()
                return
            if self.start > self.stop:
                usage()
                return
        elif len(self.args) == 2:
            self.host = self.args[1]
        else:
            usage()
            return

        # create the scanners
        for i in range(5):
            scanners.append(Scanner())

        try:
            sk.gethostbyname(self.host)
        except:
            print "hostname '%s' unknown" % self.host

        self.scan(self.host, self.start, self.stop)

    def scan(self, host, start, stop):
        self.port = start
        while self.port <= stop:
##            while threading.activeCount() < MAX_THREADS:
##                Scanner(host, self.port).start()
                self.port += 1
                queue.put((host, self.port))

def main():
    pyScan(sys.argv)

if __name__ == "__main__":
    main()

--
Rhymes (rhymes at NOSPAMmyself.com)
http://www26.brinkster.com/rhymes
" ride or die "



More information about the Python-list mailing list