Brandon's Blog

6/21/2006

Lunch Break

Much more lively day at work today, but there’s always time for some musing.

I’m thinking of moving my socket-reading routine (based on the standard select() call) over to its own thread.  This is a big step for me, as I have absolutely no clue what I’m talking about when it comes to threads.

But the thinking is this: we basically hand over control of the socket list (dictionary) to the socket selecting thread, with a strong, “no touchy” commandment to the big, bad handler thread, since the dictionary isn’t thread-safe.  It polls, or (more accurately) selects, these descriptors looking for germane read/write events (like stating files).  It then just has to pass any input along to the handler through some thread-safe route.

This is Python, so it has to be easy.  My inter-thread communication (yes, I’m sure there’s a better phrase) will be the built-in Queue object, which is a thread-safe… queue.  I add in a little Yes/No boolean flag called something like “signal” so that the socket reader can pass special information (like that the stupid Player needs to be shut down and saved immediately because he cut the cord before typing “quit”).

We’ll have to have a very small, second Queue for messages to the socket reader, since smart Players will pass “quit” messages to end their sessions.  This command, of course, would be routed from the socket thread to the handler thread.  The handler thread would save and kill off the Player (”${name} has left the game.” sent to all in-room peers, etc.).  But, the socket has to be shut down during an orderly exit, and we can’t jump over the thread’s wall without a race condition (I’m so out of my league here).  So, the handler queues a “shutdown” notice for the socket thread to pick up and deal with at its convenience.

Unfortunately, my little pseudo-daemon intermittent “task” routines (for things like denizen repopulation, server status outputs, and weather effects) cannot be run in their own thread, as they will, at times, be interacting with the same data the big boy is dealing with at every moment.  And locks on linked-lists of data (Rooms, Players, Denizens, combat, …) doing anything but slowing things down seems quite unlikely.

So, I think that would work.  If sockets weren’t so alien to the rest of the program, I don’t think it would work.  But, the little thread-safe Queue library seems to eliminate the complexity of locking.