Php script sync
I need to launch some php script in background (without waiting)and then wait until all processes are terminated,something(if you are familiar with multithreading)similar to a barrier.
Example:
//...code...
run_script('myscript1.php');//it's like an exec but doesen't wait for the script to finish
run_script('myscript2.php');//it's like an exec but doesen't wait for the script to finish
run_script('myscript3.php');//it's like an exec but doesen't wait for the script to finish
do_something();
wait_until_all_proc_are_finished();//it will wait until all script are executed
do_something_else();
//....
I created a script that should do the trick;i tested it in console and it works nice but it doesen't work on php pages,i don't understand why!
class TSync{
private $threads=array();
function tcreate($p){
$tname=tempnam(null,'THS_');//create a temp name
$p=addslashes($p);//just to be sure
$name=addslashes($tname);
$ex= 'php -r "$fp=fopen(\''.$name.'\',\'r+\');flock($开发者_运维技巧fp,LOCK_EX);include(\''.$p.'\');fclose($fp);"';
run_on_background($ex);//execute it on background
$this->threads[count($this->threads)]=$tname;
return count($this->threads)-1;//returns the thread "id"
}
function twait($id){
$f=$this->threads[$id];//recover the name
/***even this doesen't work***
$fp=fopen($f,'r');
flock($fp,LOCK_EX);
fclose($fp);
*/
echo date("H:i:s"),"#Locking on $f<br/>";
$ex= 'php -r "$fp=fopen(\''.$f.'\',\'r\');flock($fp,LOCK_EX);fclose($fp);"';
exec($ex);
unlink($f);
}
}
$t=new TSync();//create the class
$f=$t->tcreate(dirname(__FILE__).'/testth.php');//this is a test script that waits 10s
$t->twait($f);//now you should wait the script,commenting this line should result on the script not waiting
An example of the effective code launched on console (tested on windows)
start /b php.exe -r "$fp=fopen('C:\\Windows\\Temp\\THS6D7.tmp','w');flock($fp,LOCK_EX);include('C:/.../testth.php');fclose($fp);"
If i launch the code multiple times the second script will wait the first so it should work.
You should be able to solve this by using Gearman
精彩评论