Categories

Why Semaphores? (or how to bring a powerful server to its knees)

AJAX applications are not sophisticated. They’re a special variety of kludge that we’ve been conditioned as computer enthusiasts to think are special. AJAX hinges on a technology which still isn’t always fully supported (XMLHttpRequest) and requires crafting sometimes overly complex XML documents to achieve simple data transfer. But it beats standard CGI in terms of responsiveness, so web developers follow the crowds of users to the land of no-refresh websites and drag-able maps.

However, even simple applications using these cool new technologies sometimes require a bit of unique thinking to keep them from drowning in their own complexity.

Case in point, the ever popular AJAX chat. It’s a common goal, and one which has given mixed results. For a single server implementation, the requirements are simple: a common exchange area for data, sometimes in the form of a database, and some method for synchronizing clients.

The problem with implementing this via AJAX is this: HTTP, which includes the XMLHttpRequest only goes one way. Applying Comet can help things along by providing an asynchronous server-event driven control flow, but polling for state change on the current data can still bring a powerful system to a crawl, especially if operations are disk-bound. Trust me on this, disk-bound read-write operations can really slow down your snappy application.

So how to effectively communicate state change and synchronize clients without clients polling the server for new data constantly?

Semaphores. I’ve been telling my roommates and family exactly how cool semaphores are. They stare at me strangely and move along.

Semaphores solve the problem by providing an incredibly quick method for synchronization. Each client attempts to spinlock a semaphore server-side. When the server receives new data, it releases the semaphore, which is then passed around among the waiting clients, informing them each that the new data is ready in shared memory.

There are variations involving MD5 hashing, sleeplocks, or more complex socket programming, but I find this method allows me to call an AJAX method from the server asynchronously, which can greatly improve the responsiveness of an application without overloading the client with a lot of unnecessary javascript.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>