在swoole中,php可以借助其啟動子進程的方式,實現php的多進程:
<?php
$s_time = time();
echo '開始時間:'.date('H:i:s',$s_time).PHP_EOL;
//進程數
$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);
// }
//創建進程
for ($i=0; $i < $work_number; $i++) {
//創建多線程
$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;
}
//讀取管道內容
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);
}
//進程回收
swoole_process::wait();
$e_time = time();
echo '結束時間:'.date('H:i:s',$e_time).PHP_EOL;
echo '所用時間:'.($e_time-$s_time).'秒'.PHP_EOL;
?>
多線程執行結果:

作為對比,單線程結果:

提升十分明顯!
以上就是PHP使用swoole實現多線程爬蟲的詳細內容
更多學習內容請訪問:
騰訊T3-T4標准精品PHP架構師教程目錄大全,只要你看完保證薪資上升一個台階(持續更新)
以上內容希望幫助到大家,很多PHPer在進階的時候總會遇到一些問題和瓶頸,業務代碼寫多了沒有方向感,不知道該從那里入手去提升,對此我整理了一些資料,包括但不限於:分布式架構、高可擴展、高性能、高並發、服務器性能調優、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優化、shell腳本、Docker、微服務、Nginx等多個知識點高級進階干貨需要的可以免費分享給大家,需要的可以加入我的官方群
