photo credit: Steys via photopin cc

Poor mans’ multithreading in PHP

I’m currently writing an application in which multiple requests are send out to multiple servers. I do this with a CLI script I wrote in PHP (since that’s the language I’m most familiar with). I wrote a simple foreach() -loop in which I made my requests to the server, analysed the response and logged them.
Now, the problem I ran into was that PHP is a synchronous scripting language. This means that each function waits for the previous function to complete. In my situation this ment that during the foreach() -loop, each server was monitored one at a time. Needless to say, this script could take quite some time to complete as soon as the list of servers grew.

 If only I was able to separate these tasks in multiple threads… 

I tried various ways to achieve this. I wasn’t too fond on including a whole library or using an exotic compiled version of PHP; I wanted the solution to be as simple as possible. So after some research I came up with this fairly simple solution:

  • I have a master-script that runs the foreach() -loop.
  • Inside this loop I executed another PHP-script using the shell_exec() -command.

But here is the trick: I put an ampersand at the end so that the shell script would run in the background:

So, to summarize, my final foreach() -loop in my master-script looks something like this:

Since the only logic I had to do was analyse and log the result, there was no need for my master script to wait for all jobs to be finished: they handle their own logic to log their results.
As for the  sleep() -command: I did notice a strange behaviour when the scripts where fired to soon after each other. Some scripts didn’t log their results. I’m not sure if this is because they weren’t fired or because they were terminated. Perhaps there is a limit to the number of PHP CLI processes you can run in the background? Well, if you know the answer, please leave a comment.
And this summarizes on how you can create poor mans’ multithreading in PHP.

Visitors give this article an average rating of 3.8 out of 5.

How would you rate this article?

Leave a Reply