Sockets/select: how to deal with multiple connections in threads?

J.Jacob joost_jacob at hotmail.com
Sun May 26 17:56:42 EDT 2002


> [Irmen de Jong]
> > I have something that works for now, but I'd like your advice & ideas.
> 
> To answer myself;  I got some suggestions by email:
> 
> - use asyncore / Medusa and forget about threading
> - don't use a thread on each request, instead, create
>   a thread and let it live. Let the main thread deal *only*
>   with accept()-ing new connections.
> 
> Because my software (Pyro) currently is structured around threads,
> I'm trying the second suggestion. First results look promising :-)

I have been using threads combined with select, maybe this is of some help?

--------------------------------------------------------------------------
import threading
import select
from Tkinter import *

    def __init__(self, ...

        # Set up the thread to do asynchronous I/O, more threads possible
        self.listening = 1
    	self.thread1 = threading.Thread(target=self.listenThread)
        self.thread1.start()
        # Set up stop for threads
        self.master.protocol('WM_DELETE_WINDOW', self.stopThreads)

    def listenThread(self):
        "Remember that the thread has to yield control."
        while self.listening:
            is_readable = [self.cserver.socket]
            is_writable = []
            is_error = []
            r, w, e = select.select(is_readable, is_writable, is_error, 1.0)
            if r:
                print 'handling request', len(r), len(w), len(e)
                self.cserver.handle_request()

    def stopThreads(self):
        self.listening = 0
        sys.exit(1)

--------------------------------------------------------------------------

A help wanted add for a photo journalist asked the rhetorical question:

If you found yourself in a situation where you could either save
a drowning man, or you could take a Pulitzer prize winning
photograph of him drowning, what shutter speed and setting would
you use?

        -- Paul Harvey



More information about the Python-list mailing list