When I was coding Ray-Tracer project for my Computer Science studies in university, I ran into using Haskell parallel map function (map calls function for all list elements). Ray-Tracer runs reflections, shadows, ray-casts, etc. detection for every single pixel in scene and since everything is mathematical calculations, it’s paralleling is almost trivial.
Parallel map functions does all work for you – you don’t even need to know when it’s right time to fork another thread. Implementing parallel computation in Haskell was very easy and it almost gave theoretical decrease in processing time by N times (where N is processor cores count). Today I will talk a little bit about possible parallelism with PHP’s internal POSIX functions.
PHP is neither a functional language, nor is made with threading support (correct me if I’m wrong). Still, it’s possible to create parallel processes by using pcntl_* functions family. Some days ago I tried just to get something working, what uses parallel processes and can possible be extended to deal with time-consuming mathematical algorithms.
Download my sample code here (rename extension to php) and run it in terminal (it probably wont run with Apache). This code will try to compute x^3 for 0-1M integers two times, parallel runs both in one call, normal behaviour runs one after another. Output should look similar to this:
juokaz@thinkpad:~/Desktop/php/parallel$ php run.php We start I am the child, pid = 0 I am the parent, pid = 2004 yep, finished, I have 2004 ID yep, finished, I have 0 ID Ran parallel 5.81009602547 seconds yep, finished, I have 1 ID yep, finished, I have 2 ID Ran normal 9.76671719551 seconds
As you can see, parallel computation on dual core processor ran almost 2x faster. And yes, it does use both cores simultaneously.
If you want to look more deeply, there is great article called Thorough look at PHP’s pcntl_fork(). You will quite quickly find that there are problems when using pcntl_fork, because it basically clones running process and then continues. Everything you define before forking child process will be accessible inside child – it’s not always what you really want.
Parallel processes can be easily simulated by using asynchronous calls (over HTTP, for example) from one script to others, but for something more calculations-based, using pcntl_fork() can be much more practical. But I will probably still chose asyncronous calls over parallelizing because they are much more flexible.







