I’m at a point in my PHP server-side API where I am making lots of MySQL queries and I’d like to speed it up by having mutliple threads working on different queries and then return the results.
But how do I make another thread in PHP? I am passing around POST params, so a simple shell_exec() could work, but seems kinda of unsafe. Options I’m considering:
1) Make a cURL request using the parameters I have, process the JSON from the request and then return
2) Call a shell_exec() with PHP CLI and somehow (how would I do this??) process the response in PHP
what are the best options here?
There is no threading support in PHP. You can however use the
pcntlextension to spawn and manage forks, but it would be best to have a second look at your algorithms if you reached the conclusion that things should be done with threading.An option for processing long running operations asynchronously would be to store them in a database, and have a background worker process take them from the database, calculate the results, then store the results in the database. Then the front facing script would look them up in the database to see if they’re completed and what the result is.