asynchat and threading

Rob Snyder arkham at gmail.com
Wed Nov 24 09:57:44 EST 2004


Greetings -

I've embarked on a small learning project, trying to get a better grasp of
the asyncore and asynchat modules. The project involves building a simple
instant messenger application for use on our LAN - nothing heavy duty, as
99% of my reason for doing this is just to learn.

I got my server portion working well, and I think I understand the basics.
Where I'm getting stuck is on the client side, where I'm trying to involve
both the asyncore / asynchat stuff in a multithreaded app.

Assume for this that I have a window open with an active chat session, and
an open connection to the server. At any moment in time, a message coule be
received on the connection from the server, or the user could start typing
their own message (and ultimately press enter to send it). Or, for that
matter, the user could close the window or resize it, etc.

I've got to be listening for incoming messages while also letting the UI run
to handle events, while checking the event queue for things I care about
(such as the enter key). I may also, in theory, still be in the process of
sending a prior message out.

I noticed early on that once I call asyncore.loop(), I surrender control to
the asyncore library. I don't want to get into a polling situation, so I
like that asyncore has taken over and is effectively waiting on incoming or
outgoing data.

Since I still need to run my UI, though, started a seperate thread for the
asyncore stuff. I figured I would establish a queue that the asyncore could
use to deliver messages to the UI, and I would just have the UI call the
"push" method to get messages sent.

Then, of course, the ugliness ensued. First, I can't have the UI wait on
both the UI's event queue and the queue I established for communication, so
I'd have to go back to polling between the two. Second, after I read
through the asynchat module, I realized that the producer fifo is just a
list, and when I call push, not only is there no inherent synchronization,
I would actually invoking the code to deliver the message in the UI thread
(so now I have two threads running through the same instance of my
async_chat object, which seems dangerous).

There *must* be some way to use this asyncore stuff on the client side, but
I'm not seeing it. I'm about to bail on it for the client, but I thought
I'd put this out there to see if anyone can help me see a different
approach to this stuff.

Thanks for the help!

Rob



More information about the Python-list mailing list