I've gotten several requests recently from developers wondering how to add multithreading to AsyncSocket and/or the Cocoa HTTP Server. So I whipped up a quick version of the cocoa http server that demonstrates how by splitting incoming connections between multiple threads.
You can download the MultiThreadedHTTPServer from here.
A quick explanation of the code:
Anytime AsyncSocket accepts a new connection it will fire 2 delegate methods:
So all one has to do is implement the these delegates, and return the run loop of a background thread in the second delegate method. I'm sure there are various ways to do this. Here's how I architected it in the sample code:
When the server first starts, it splits off multiple background threads. Each thread stores a reference to its run loop in an array, and then starts the run loop, and runs it indefinitely. This array can then be consulted to obtain a reference to the background thread/runloop.
But that was a bit too easy, so I made it a little smarter.
In addition to keeping an array of run loop references, the code also keeps track of how many connections each thread/runloop currently has attached to it. So when a new connection comes it, the code chooses the run loop with the smallest load. So it does a wee bit of load balancing.
The number of background threads is set in a "#define" statement. It can be adjusted as desired.