1

I want to optimize part of my code to improve performance.Since my application make use of commandline tool , i think it would certainly improve performance to execute lines of code in parallel rather than executing code sequentially

<?php
$value = exec("command goes here"); //this takes time
/* Some instructions here that don't depend on $value */
/* Some instructions here that don't depend on $value */

$result = $value*2 ; //this is just a dumb example

?>  

I want to execute the codes that don't depend on value at the same time as $value so that the whole script execute faster rather that waiting for exec() to complete

user2650277
  • 6,289
  • 17
  • 63
  • 132

2 Answers2

0

Unfortunately PHP always despond you in parallelism, concurrent programming, .... And I never know that why PHP doesn't support these important things and WHEN PHP WANT TO SUPPORT THESE.

But maybe you want to use Fork in php (if you know the problems AND Troubles in Fork )

http://php.net/manual/en/function.pcntl-fork.php

https://codereview.stackexchange.com/questions/22919/how-to-fork-with-php-4-different-approaches

Oladipo
  • 1,579
  • 3
  • 17
  • 33
abbasian
  • 1
  • 1
0

For a quick and dirty way of releasing your php thread from a blocking exec thread, you can simply append the command with a "&" or "& disown". In the example below I also redirected all errors and stdout to /dev/null. (I assume a linux system and just used a simple command that might take some amount of time...)

$command = "mv oldFolder/hugeFile.txt newFolder/hugeFile.txt >> /dev/null 2>&1 &";
$value=exec($command);

If you really need the return value from $command just remove the >> /dev/null 2>&1 bit.

denjello
  • 531
  • 3
  • 13
  • I really need the output so i just need to add a `&`for it to go in background.Will other parts of the script execute as normal – user2650277 Oct 18 '14 at 13:55
  • I mean when we reach $result , will php wait for output from `$value` – user2650277 Oct 18 '14 at 14:20
  • well, you could have your command in shell write to a file / database when it is done and have some other watcher in php / javascript look for the file... – denjello Oct 18 '14 at 19:56
  • Looks more of a hassle and seems to take more time since write to file involve reading/writing to disk – user2650277 Oct 23 '14 at 15:38