0

How can I run a PHP function in background, not a process? For instance, I have to do:

(php code)
1º) retrieve data from database#1
2º) retrieve data from database#2
3º) If #1 and #2 have finished, do my calculations.

Functions #1 and #2 are also PHP code. I don't want to use "exec" or "system", as they are not external processes, they are also PHP code! I imagine there should exist some smart way to run a PHP function or line in the background, just that. Any idea?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
cenicero
  • 1
  • 1
  • 2

4 Answers4

3

PHP doesn't do multi-threading*, so what you want to do is not possible inside the same script.

You would need to start a separate PHP process that works through a separate script.

*) there is pcntl_fork for CLI and possibly CGI mode but it has pitfalls, documentation and examples on this seem sparse, it is limited to Unix/Linux, and I am assuming you are in a web page context anyway where it doesn't work.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
0

Php does support threading (requires PECL pthreads >= 0.34)

you will find an example here http://php.net/manual/en/thread.start.php

Ramast
  • 7,157
  • 3
  • 32
  • 32
0

You could setup a cURL multi handler, which can run different scripts (and get the data from them) in parallel. This, in my opinion, is the best option for running multi-threaded scripts in PHP.

You'd have to change things around though - the function(s) that you'd want to run in the background would have to be moved into their own script, and called individually by the cURL handler.

http://php.net/manual/en/function.curl-multi-exec.php

Here's some examples of use:

http://codestips.com/php-multithreading-using-curl/

https://web.archive.org/web/20091014034235/http://www.ibuildings.co.uk/blog/archives/811-Multithreading-in-PHP-with-CURL.html

patstuart
  • 1,931
  • 1
  • 19
  • 29
xil3
  • 16,305
  • 8
  • 63
  • 97
0

As other posters said, threading is not possible directly.

As far as your specific question, there are ways of doing it. You could use MySQLi::multi_query(). The first query needs to finish before you can use the results from the second query

$mysqli->multi_query($sql1 . ';' . $sql2);
$result1 = $mysqli->store_result();
$rows1 = $result1->fetch_all();
$result2 = $mysqli->store_result();
$rows2 = $result2->fetch_all();

Both queries are executed side by side. The results are returned synchronously, but it works.

You could also emulate threads using a register_tick_function(). There are some docs online about to actually use ticks for threading. But I have to warn you, it's usually a very bad idea to try to abuse them in this way, since it's not really true threading it won't behave like it (statements are still executed in order, so a blocking statement will block everything).

ircmaxell
  • 163,128
  • 34
  • 264
  • 314