A Multithreaded Web Server in Perl
By Randal L. Schwartz
Last month, I looked at how to maintain a stateful "conversation" using a child process per "session." While this is easy to do (thanks to the HTTP::Daemon module in LWP), it can get rather expensive if you're trying to maintain 15 or 20 conversations.
In this column, I'll show a different approach that still requires a small number of code lines but has its own advantages and disadvantages. This time, I'll create a single, multithreaded mini Web server to handle all the conversations in parallel for a particular Web page.
This approach has the advantage of requiring minimal resources on the server machine. However, it doesn't scale well to hundreds of simultaneous conversations. For that, a solution like mod_perl embedded inside the Apache server is probably a better deal.
Another advantage of this single, multithreaded mini Web server is that a single process is sharing the collective state of all transactions. Using this technology as a base, you could build a nice chat server, where individual threads are maintained, and thread interaction is enabled.
As in the previous column, I'm using the "Eliza" module to demonstrate a nontrivial, but easily viewable, interaction that requires state. One nice thing about this module is that the computation time per form submission is rather small. Because the mini Web server can handle only one submission at a time, all other clients will be blocked until the computation is complete.