Multi-Threaded PHP

PHP does not natively provide a way to create a true multi-threaded application. Yet, with the right combination of technologies it is possible to emulate multiple threads. If PHP is running inside of a web server, and has either read/write access to the file system or your application has access to a database then it is possible to open a socket, create a HTTP request which contacts itself and thus creates a segment in memory to run the new PHP task. The file system or database service as the IO for the thread to create a monitor or pass events back and forth to the new memory space.

While this might seem simple there are a few caveats. The first is to make sure that when you write to the socket to emulate a HTTP request that you specify the header Connection:close; to tell the HTTP server that even if the connection is lost to keep the process running. Secondly read the first 128 kb from the socket and process the headers to ensure the request did not send an error code, but be sure to disable all output buffering and call flush() explicitly after writing 128 kb to the output buffer otherwise the initial request will block.

Well, that is the simplest explanation.

A diagram will follow soon

Post new comment

The content of this field is kept private and will not be shown publicly.