PHP Multithreading – Faking It
PHP doesn’t really support multi-threading per se but there are ways to do “fake” multithreading. Here’s one I saw in the PHPClasses.org newsletter – Multi-thread Simulation.
Note that this class is intedend for use on a webserver, as opposed to running PHP scripts from a command line (or similar). Check the end of this post for some alternatives you can try if you’re using PHP as a stand-alone scripting language.
Now, I’m going to be lazy and just copy the description of the class from the project page :)
This class can emulate the execution of program threads using separate HTTP requests to the same script.
It establishes an HTTP connection to the same Web server to execute the same PHP script. It sends a request passing the name a function to execute and an argument to be passed to that function.
The requested script executes some code that detects the thread execution request and calls the specified function.
When the thread request script ends, the return values of the called function is returned as a serialized string.
The calling script can execute other tasks while the thread script runs. The results may be collected later when the thread script ends.
PHP Process Control Functions (via pcntl_fork())
PCNTL lets you do simple multithreading “*nix-style” – you can fork the current process and work from there. However, this extension is not enabled by default and it most likely wouldn’t be enabled on a webserver, too.
Multi-threading strategies in PHP
Here’s another article about PHP multi-threading I found on Google. It’s an example class that implements a form of multithreading. I haven’t examined the code in detail but on a first glance it looks like it might not work in a webserver enviroment.
So there you have it. Personally I don’t need multi-threading in any of my current PHP projects, but it seems like a useful thing to note for future reference.