2011-04-08 36 views
2

我需要在后台启动一些php脚本(无需等待),然后等到所有进程终止,类似于屏障的东西(如果您熟悉多线程)。Php脚本同步

例子:

//...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(); 
//.... 

我创建了一个脚本,应该做的伎俩;我在控制台测试它和它的作品不错,但它doesen't在PHP页面的工作,我不明白为什么!

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 

在控制台上推出有效的代码示例(在Windows上进行测试)

start /b php.exe -r "$fp=fopen('C:\\Windows\\Temp\\THS6D7.tmp','w');flock($fp,LOCK_EX);include('C:/.../testth.php');fclose($fp);" 

如果我的代码多次推出第二脚本将等待第一所以它应该工作。

+0

所以究竟是什么你问什么来解决这个问题? – 2011-04-08 23:17:09

+0

问为什么它不起作用时,在网页的上下文(而不是CLI) – Ben 2011-04-08 23:31:56

+0

本是正确的: 我贴的代码应该做我所问,但在PHP doesen't工作,我不知道为什么; 如果你可以修复它或发布一些其他的解决方案,请做。 无论如何,我最近发现我使用的PHP版本(5.3.0)在fclose上解锁资源(php> 5.3.2 doesen't不再那么做),我不知道更新是否可以修复它。 – Plokko 2011-04-09 08:07:51

回答

0

您应该能够通过使用Gearman

+0

它是一个php扩展,它不是php代码;我的代码也应该(理论上)工作,但它不会这样,如果任何人都可以告诉我为什么它没有工作,它已经是完美的了。 – Plokko 2011-04-24 14:57:14