Nov 262012
 
Article Apache

For a long time, PHP has been lacking the functionality to write programs able to run several threads in parallel.

Currently, it is possible to install a PHP interpreter with pthreads (POSIX threads) support. However, the standard PHP distributions do not include this build.

In order to obtain a multithread-enabled PHP interpreter it, is necessary to compile it from source, including in the configure step the option “–enable-maintainer-zts” (–enable-zts on Windows). This generates a  “thread-safe” interpreter that can be run under an Apache server with multithreading (worker MPM), instead of a simple multiprocessing Apache server (pre-fork MPM). However, this type of installation is generally not recommended because, even if the PHP core is thread-safe, some of the extensions used might not be thread-safe.

In this post, we will explore the existing possibilities to implement multi-threading in PHP, and the considerations to take into account in  doing so.

Poor man’s multithreading in PHP

First of all, we should ask ourselves if we really need all the functionality of a multithreading implementation.

We migth be interested in multithreading because our scripts need to execute some tasks that take a long time to be done. These tasks should not prevent the main program from continuing to execute. Those taks might be heavy queries to a database, or connections to external servers through the network, taking dozens of seconds each one of them, but that could be run in parallel.

In most of these cases, a simple multithreading mock-up based on pcntl_fork can be good enough.

This “poor man’s” implementation actually creates a system process for each of the tasks we run in parallel, and therefore lacks the advantage of multithreading in terms of resource consumption and memory sharing. The great advantage is that there is no need to compile the interpreter from source code.

To try this implementation, start by downloading and uncompressing the “thread.zip” file.

Next, write a test script  “threads_test.php”. The content to write in this script is:

Running this script, we get the expected output:

 Posted by at 8:01 pm

  2 Responses to “Multithreading in PHP”

  1. Hi,
    can you upload the file again? There’s a 500 at the moment.

 Leave a Reply

(required)

(required)