在swoole中,php可以借助其啟動(dòng)子進(jìn)程的方式,實(shí)現(xiàn)php的多進(jìn)程:
<?php $s_time = time(); echo '開始時(shí)間:'.date('H:i:s',$s_time).PHP_EOL; //進(jìn)程數(shù) $work_number=6; // $worker=[]; //模擬地址 $curl=[ 'https://blog.csdn.net/feiwutudou', 'https://wiki.swoole.com/wiki/page/215.html', 'http://fanyi.baidu.com/?aldtype=16047#en/zh/manager', 'http://wanguo.net/Salecar/index.html', 'http://o.ngking.com/themes/mskin/login/login.jsp', 'https://blog.csdn.net/marksinoberg/article/details/77816991' ]; //單線程模式 // foreach ($curl as $v) { // echo curldeta($v); // } //創(chuàng)建進(jìn)程 for ($i=0; $i < $work_number; $i++) { //創(chuàng)建多線程 $pro=new swoole_process(function(swoole_process $work) use($i,$curl){ //獲取html文件 $content=curldeta($curl[$i]); //寫入管道 $work->write($content.PHP_EOL); },true); $pro_id=$pro->start(); $worker[$pro_id]=$pro; } //讀取管道內(nèi)容 foreach ($worker as $v) { echo $v->read().PHP_EOL; } //模擬爬蟲 function curldeta($curl_arr) {//file_get_contents echo $curl_arr.PHP_EOL; file_get_contents($curl_arr); } //進(jìn)程回收 swoole_process::wait(); $e_time = time(); echo '結(jié)束時(shí)間:'.date('H:i:s',$e_time).PHP_EOL; echo '所用時(shí)間:'.($e_time-$s_time).'秒'.PHP_EOL; ?>
多線程執(zhí)行結(jié)果:
作為對(duì)比,單線程結(jié)果:
提升十分明顯!