1

I am new to php and trying to run three functions in parallel. I have a code similar to the following:

Call function1(…….);  //all these function are located in separate host server
Call function2(…….);  
Call function3(…….);

All the above functions will be running for 5 min or more. Therefore, I really need to call them in parallel, if not my program will run for 15 min or more. any help would be greatly appreciated.

Justin k
  • 1,104
  • 5
  • 22
  • 33
  • PHP is not a threaded/parallellizable language. Run 3 separate PHP scripts, each calling one of those functions. – Marc B Jun 04 '13 at 20:05
  • Similar http://stackoverflow.com/questions/9684290/executing-functions-in-parallel http://stackoverflow.com/questions/2998314/executing-functions-parallelly-in-php – PiLHA Jun 04 '13 at 20:05
  • Without knowing what exactly are 'functions' in your example, it's hard to recommend anything. In some cases you may need to look for something like [Gearman](http://php.net/manual/en/book.gearman.php), in some there might be already some 'pooling' technique implemented in your particular tools of trade. – raina77ow Jun 04 '13 at 20:06
  • There are just too many duplicates for this question. Research first, ask later. – Maxim Kumpan Jun 04 '13 at 20:08

1 Answers1

2

You can use pThread , here is a good place to start :

Example

$ts = array();
$ts[] = new Call("function1");
$ts[] = new Call("function2");
$ts[] = new Call("function3");

foreach($ts as $t) {
    $t->start();
}

foreach($ts as $t) {
    $t->join();
}

Simple Thread Class

class Call extends Thread {

    function __construct($func) {
        $this->func = $func;
    }

    function run() {
        call_user_func($this->func);
    }
}
Community
  • 1
  • 1
Baba
  • 94,024
  • 28
  • 166
  • 217
  • Note: [pThread is experimental](http://www.php.net/manual/en/intro.pthreads.php#usernotes). – Frank Farmer Jun 04 '13 at 20:19
  • 2
    Using it in production for a while now .... – Baba Jun 04 '13 at 20:21
  • @Baba Thank you so much for explaning this to me in detail. I was trying to install pthread in my computer and my php code keep saying `Fatal error: Class 'Thread' not found`. can you please tell me what should I install to run this pthread. I would greatly apriciate your help – Justin k Jul 01 '13 at 04:25