php - 多线程

1. php5.3 以上版本(必须是线程安全),使用php_pthreads扩展,可以使php真正地支持多线程。

2. 下载安装

  1. windows 下载地址 windows 注意需要将“pthreadVC2.dll”拷贝到windows目录下。
  2. linux 下载地址 linux
  3. 参考文档 文档

3. 测试代码 使用多线程平均时间:8.5S, 使用foreach循环平均时间:22.0S


<?php
//多线程测试
class myThread extends Thread{
    public $url     = null;
    public $data    = null;

    public function __construct($url){
        $this->url = $url;
    }

    public function run(){
        $this->data = model_http_curl_get($this->url);
        $file = './pic/' . md5($this->url) . '.html';
        file_put_contents($file, $this->data);
    }
}


function getByThread($urls){
    $thread_array = array();
    foreach ($urls as $key => $value){
        $thread_array[$key] = new myThread($value["url"]);
        $thread_array[$key]->start();
    }
}

function getByforeach($urls){
    foreach($urls as $key=>$value){
        echo $key;
        $data = model_http_curl_get($value["url"]);
        $file = './pic/' . $key . '.html';
        file_put_contents($file, $data);
    }
}



 function model_http_curl_get($url,$userAgent=""){
    $userAgent = $userAgent ? $userAgent : 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)';
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);  
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_TIMEOUT, 5);
    curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}


//开始测试
$urls_array = array();
for ($i=1; $i <= 30; $i++){

    //$urls_array[] = array("url" => "http://www.baidu.com/s?wd=".mt_rand(10000,20000));
    $urls_array[] = array("url" => "http://tu.duowan.com/gallery/86760.html#p". $i);
}
//多线程
getByThread($urls_array);

//foreahc循环 - 平均 22.0s
//getByforeach($urls_array);
?>

你可能感兴趣的:(php - 多线程)