Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concurrency in PHP

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?

like image 868
lollercoaster Avatar asked Apr 26 '12 02:04

lollercoaster


People also ask

Is PHP good for concurrency?

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.

Can PHP handle concurrent requests?

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.

What is the concept of concurrency?

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.

What is an example of concurrency?

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.


2 Answers

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.

like image 71
rid Avatar answered Sep 30 '22 08:09

rid


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.

like image 35
Will Avatar answered Sep 30 '22 10:09

Will