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?
This also makes PHP the perfect platform for implementing a parallel concurrency API based on CSP (message passing over channels), because PHP itself is shared nothing - PHP threads operate in their own virtual address space by default, and so may only share memory by communicating.
PHP does not handle requests. The web server does. For Apache HTTP Server , the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.
Concurrency is the concept of executing two or more tasks at the same time (in parallel). Tasks may include methods (functions), parts of a program, or even other programs. With current computer architectures, support for multiple cores and multiple processors in a single CPU is very common.
Multiprogramming, or running a lot of programs concurrently (the O.S. has to multiplex their execution on available processors). For example: downloading a file. listening to streaming audio.
There is no threading support in PHP. You can however use the pcntl
extension 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.
Check out the pcntl extension. PHP doesn't support true threading at all, so you'll have to implement pseudo-threads by fork()ing. Note that fork()ing a process is much "heavier" than spawning a thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With