PHP多線程的執行個體(PHP多線程類)

來源:互聯網
上載者:User

通過WEB伺服器來實現PHP多線程功能。

當然,對多線程有深入理解的人都知道通過WEB伺服器實現的多線程只能模仿多線程的一些效果,並不是真正意義上的多線程。

但不管怎麼樣,它還是能滿足我們的一些需要的,在需要類似多線程的功能方面還是可以採用這個類。

 代碼如下 複製代碼

 

    /**
    * @title: PHP多線程類(Thread)
    * @version: 1.0
    * @author: phper.org.cn < web@phper.org.cn >
    * @published: 2010-11-2
    *
    * PHP多線程應用樣本:
    * require_once 'thread.class.php';
    * $thread = new thread();
    * $thread->addthread('action_log','a');
    * $thread->addthread('action_log','b');
    * $thread->addthread('action_log','c');
    * $thread->runthread();
    *
    * function action_log($info) {
    * $log = 'log/' . microtime() . '.log';
    * $txt = $info . "rnrn" . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn";
    * $fp = fopen($log, 'w');
    * fwrite($fp, $txt);
    * fclose($fp);
    * }
    */
    class thread {
    var $hooks = array();
    var $args = array();
    function thread() {
    }
    function addthread($func)
    {
    $args = array_slice(func_get_args(), 1);
    $this->hooks[] = $func;
    $this->args[] = $args;
    return true;
    }
    function runthread()
    {
    if(isset($_GET['flag']))
    {
    $flag = intval($_GET['flag']);
    }
    if($flag || $flag === 0)
    {
    call_user_func_array($this->hooks[$flag], $this->args[$flag]);
    }
    else
    {
    for($i = 0, $size = count($this->hooks); $i < $size; $i++)
    {
    $fp=fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']);
    if($fp)
    {
    $out = "GET {$_SERVER['PHP_SELF']}?flag=$i HTTP/1.1rn";
    $out .= "Host: {$_SERVER['HTTP_HOST']}rn";
    $out .= "Connection: Closernrn";
    fputs($fp,$out);
    fclose($fp);
    }
    }
    }
    }
    }


使用方法:

 代碼如下 複製代碼

    $thread = new thread();
    
    $thread->addthread('func1','info1');
    
    $thread->addthread('func2','info2');
    
    $thread->addthread('func3','info3');
    
    $thread->runthread();


說明:

addthread() 是添加線程函數,第一個參數是函數名,之後的參數(可選)為傳遞給指定函數的參數。

runthread() 是執行線程的函數。

例2.利用curl實現多線程下載圖片

其實是php利用curl實現的一個多線程類),有了這個類,我們也可利用該類執行多線程任務了!

 代碼如下 複製代碼

 

    <?php
    class curl_multi{
        private $url_list=array();
        private $curl_setopt=array(
            'CURLOPT_RETURNTRANSFER' => 1,//結果返回給變數
            'CURLOPT_HEADER' => 0,//是否需要返回HTTP頭
            'CURLOPT_NOBODY' => 0,//是否需要返回的內容
            'CURLOPT_FOLLOWLOCATION' => 0,//自動跟蹤
            'CURLOPT_TIMEOUT' => 6//逾時時間(s)
        );
        function __construct($seconds=30){
            set_time_limit($seconds);
        }
        /*
         * 設定網址
         * @list 數組
         */
        public function setUrlList($list=array()){
            $this->url_list=$list;
        }
        /*
         * 設定參數
         * @cutPot array
         */
        public function setOpt($cutPot){
            $this->curl_setopt=$cutPot+$this->curl_setopt;
        }
        /*
         * 執行
         * @return array
         */
        public function execute(){
            $mh=curl_multi_init();
            foreach($this->url_list as $i=>$url){
                $conn[$i]=curl_init($url);
                foreach($this->curl_setopt as $key => $val){
                    curl_setopt($conn[$i],preg_replace('/(CURLOPT_w{1,})/ie','$0',$key),$val);
                }
                curl_multi_add_handle($mh,$conn[$i]);
            }
            $active=false;
            do{
                $mrc=curl_multi_exec($mh,$active);
            }while($mrc == CURLM_CALL_MULTI_PERFORM);
    
            while($active and $mrc == CURLM_OK){
                if(curl_multi_select($mh) != -1){
                    do{
                        $mrc=curl_multi_exec($mh,$active);
                    }while($mrc == CURLM_CALL_MULTI_PERFORM);
                }
            }
            $res=array();
            foreach($this->url_list as $i => $url){
                $res[$i]=curl_multi_getcontent($conn[$i]);
                curl_close($conn[$i]);
                curl_multi_remove_handle($mh,$conn[$i]);//釋放資源  
            }
            curl_multi_close($mh);
            return $res;
        }
    }

php使用多線程下載類樣本:下載遠程圖片

 代碼如下 複製代碼


    $curl_mul=new curl_multi();
    $curl_mul->setUrlList(array('yun_qi_img/logo.jpg','yun_qi_img/logo.jpg','yun_qi_img/logo.jpg'));
    $a=$curl_mul->execute();
    $i=1;
    foreach($a as $v){
        $filename=$i.'.gif';
        $fp2=@fopen($filename,'a');
        fwrite($fp2,$v);
        fclose($fp2);
        $i++;
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.