阿里技术学习博客

分享学习经验

IT博客 联系 聚合 管理
  42 Posts :: 1 Stories :: 36 Comments :: 0 Trackbacks

记录一下两个php5实现多任务处理的方式:
一、针对proc_open打开管道的方式
<?php

echo "Programstartsat".date('h:i:s').".\n";

$timeout=10;

$streams=array();

$handles=array();

/*Firstlaunchaprogramwithadelayofthreeseconds,then

onewhichreturnsafteronlyonesecond.*/

$delay=30;

for($id=0;$id<=10;$id++){

 $error_log="".$id.".txt";

 $descriptorspec=array(

  0=>array("pipe","r"),

  1=>array("pipe","w"),

  2=>array("file",$error_log,"w")

 );

 $cmd='sleep '.$delay.';echo "Finishedwithdelayof'.$delay.'".';
echo $cmd."--\n";


 

 $handles[$id]=proc_open($cmd,$descriptorspec,$pipes);

 $streams[$id]=$pipes[1];

 $all_pipes[$id]=$pipes;

 $delay-=2;

}

while(count($streams)){

echo "while------\n";
 $read=$streams;

 stream_select($read,$w=null,$e=null,$timeout);

 foreach($read as $r){

  $id=array_search($r,$streams);

  echo stream_get_contents($all_pipes[$id][1]) . "-\n";

  if(feof($r)){

   fclose($all_pipes[$id][0]);

   fclose($all_pipes[$id][1]);

   $return_value=proc_close($handles[$id]);
echo "--".$return_value."\n";

   unset($streams[$id]);

  }

 }

}

?>



二、针对stream_socket_client打开socket的方式

清单1.同时请求多个HTTP页面

<?php

echo"Programstartsat".date(''h:i:s'').".\n";

$timeout=10;

$result=array();

$sockets=array();

$convenient_read_block=8192;

/*Issueallrequestssimultaneously;there''snoblocking.*/

$delay=15;

$id=0;

while($delay>0){

$s=stream_socket_client("phaseit.net:80",$errno,

$errstr,$timeout,

STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);

if($s){

$sockets[$id++]=$s;

$http_message="GET/demonstration/delay?delay=".

$delay."HTTP/1.0\r\nHost:phaseit.net\r\n\r\n";

fwrite($s,$http_message);

}else{

echo"Stream".$id."failedtoopencorrectly.";

}

$delay-=3;

}

while(count($sockets)){

$read=$sockets;

stream_select($read,$w=null,$e=null,$timeout);

if(count($read)){

/*stream_selectgenerallyshuffles$read,soweneedto

computefromwhichsocket(s)we''rereading.*/

foreach($readas$r){

$id=array_search($r,$sockets);

$data=fread($r,$convenient_read_block);

/*Asocketisreadableeitherbecauseithas

datatoread,ORbecauseit''satEOF.*/

if(strlen($data)==0){

echo"Stream".$id."closesat".date(''h:i:s'').".\n";

fclose($r);

unset($sockets[$id]);

}else{

$result[$id].=$data;

}

}

}else{

/*Atime-outmeansthat*all*streamshavefailed

toreceivearesponse.*/

echo"Time-out!\n";

break;

}

}

?>

如果运行此清单,您将看到如下所示的输出。

清单2.从清单1中的程序获得的典型输出

Programstartsat02:38:50.

Stream4closesat02:38:53.

Stream3closesat02:38:56.

Stream2closesat02:38:59.

Stream1closesat02:39:02.

Stream0closesat02:39:05.

posted on 2008-11-21 12:09 阿里爸爸 阅读(848) 评论(1)  编辑 收藏 引用 所属分类: 技术

Feedback

# re: 记录一下两个php5实现多任务处理的方式 2008-12-13 16:40 dell笔记本
以前写过类似的  回复  更多评论
  

只有注册用户登录后才能发表评论。