php中stream_select的使用实习



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

$timeout=10;
$result=array();
$sockets=array();
$convenient_read_block=8192;

$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)){
        foreach($read as $r){
            $id=array_search($r,$sockets);
            $data=fread($r,$convenient_read_block);
            if(strlen($data)==0){
                echo"Stream ".$id." closes at ".date('h:i:s').".\n";
                fclose($r);
                unset($sockets[$id]);
            }else{
                $result[$id].=$data;
            }
        }
    }else{
        echo"Time-out!\n";
        break;
    }
}



<?php
echo "Program starts at ". date('h:i:s') . ".\n";

$timeout=10;
$streams=array();
$handles=array();

$delay=3;
for ($id=0; $id <= 1; $id++) {
    $error_log="/tmp/error" . $id . ".txt";
    $descriptorspec=array(
            0 => array("pipe", "r"),
            1 => array("pipe", "w"),
            2 => array("file", $error_log, "w")
            );          
    $cmd='sleep ' . $delay . '; echo "Finished with delay of ' .
        $delay . '".'; 
    $handles[$id]=proc_open($cmd, $descriptorspec, $pipes);
    $streams[$id]=$pipes[1];
    $all_pipes[$id]=$pipes;
    $delay -= 2;
}

while (count($streams)) {
    $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]);
        if (feof($r)) {
            fclose($all_pipes[$id][0]);
            fclose($all_pipes[$id][1]);
            $return_value=proc_close($handles[$id]);
            unset($streams[$id]);
        }       
    }   
}

这里的关键在于 PHP 启动了两个独立子进程,取回待完成的第一个进程的输出,然后取回第二个进程的输出,即使后者启动得较早。如果主机是多处理器计算机,并且操作系统已正确配置,则操作系统本身负责将各个子程序分配给不同的处理器。这是在多处理器主机中良好应用 PHP 的一种方法。






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值