Advice on sockets and threads

Gonçalo Rodrigues op73418 at mail.telepac.pt
Wed May 21 12:20:24 EDT 2003


I have a class Session which is basically a thread (that is, it derives
from threading.Thread) controlling a socket. The run method is basically
a loop of the form:

while not self.exit:
    #Early check to not block on empty queue.
    if self.queue:
        writedata = self.queue.get()
        self.conn.write(data)
    if select.select([self.conn], [], [])[0] == [self.conn]:
        data = self.conn.read()
        self.parent.queue.append(ConnectionInputEvent(self, data))

It first writes to the connection (a socket + telnet usually) if there
is something waiting to be written in the queue, then reads whatever is
there and pushes it to the "parent"'s queue.

self.exit is just a flag allowing the "parent" thread to signal "Die,
please". It's a temporary scheme, I'll prolly ditch it.

Anyway, while staring at the code, I noticed that this would degenerate
into a busy loop if there is nothing to read and nothing to write. It
just doesn't seem the right thing to do. So, how you guys do it? Spawn a
new thread whose only responsability is standing by the queue, peel what
data is there and write it to the socket? Or is the above just fine and
dandy? Some other scheme?

Bear with me, this is the first time I'm doing socket stuff.

Let me add that the envisaged scenario for the application is having
only a handfull of connections opened at a time, usually telnet, steered
by a human user: MUD's, for example.

TIA, with my best regards,
G. Rodrigues




More information about the Python-list mailing list