注:php多進程通常應用在php_cli命令行中執行php腳本,作進程任務時要檢查php是否開啓了pcntl擴展,(pcntl是process control進程管理的縮寫)php
pcntl_fork — 在當前進程當前位置產生分支(子進程)。
一個fork子進程的基礎示例:面試
$pid = pcntl_fork(); //父進程和子進程都會執行下面代碼 if ($pid == -1) { //錯誤處理:建立子進程失敗時返回-1. die('could not fork'); } else if ($pid) { //父進程會獲得子進程號,因此這裏是父進程執行的邏輯 pcntl_wait($status); //等待子進程中斷,防止子進程成爲殭屍進程。 } else { //子進程獲得的$pid爲0, 因此這裏是子進程執行的邏輯。 }
好比有一個比較大的數據文件要處理,這個文件由不少行組成。若是單進程執行要處理的任務,量很大時要耗時比較久。這時能夠考慮多進程。數據庫
來看一道面試題,有一個1000萬個元素的int數組,須要求和,平均分到4個進程處理,每一個進程處理一部分,再將結果統計出來,代碼如數組
<?php $arrint = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];//假設不少 $arrint = array_chunk($arrint,4,TRUE); for ($i = 0; $i < 4; $i++){ $pid = pcntl_fork(); if ($pid == -1) { die("could not fork"); } elseif ($pid) { echo $pid; echo "I'm the Parent $i\n"; } else { // 子進程處理 // $content = file_get_contents("prefix_name0".$i); $psum = array_sum($arrint[$i]); echo $psum . "\n";分別輸出子進程的部分求和數字,可是沒法進行想加,由於進程互相獨立 exit;// 必定要注意退出子進程,不然pcntl_fork() 會被子進程再fork,帶來處理上的影響。 } } // 等待子進程執行結 while (pcntl_waitpid(0, $status) != -1) { $status = pcntl_wexitstatus($status); echo "Child $status completed\n"; }
<?php $arrint = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];//假設不少 $arrint = array_chunk($arrint,4,TRUE);//把數組分爲4個 // 建立消息隊列,以及定義消息類型(相似於數據庫中的庫) $id = ftok(__FILE__,'m');//生成文件key,惟一 $msgQueue = msg_get_queue($id); const MSG_TYPE = 1; msg_send($msgQueue,MSG_TYPE,'0');//給消息隊列一個默認值0,必須是字符串類型 //fork出四個子進程 for ($i = 0; $i < 4; $i++){ $pid = pcntl_fork(); if ($pid == -1) { die("could not fork"); } elseif ($pid) { echo $pid; echo "I'm the Parent $i\n"; } else { // 子進程處理邏輯,相互獨立,解決辦法,放到內存消息隊列中 $part = array_sum($arrint[$i]); implode_sum($part);//合成計算出的sum exit;// 必定要注意退出子進程,不然pcntl_fork() 會被子進程再fork,帶來處理上的影響。 } } function implode_sum($part){ global $msgQueue; msg_receive($msgQueue,MSG_TYPE,$msgType,1024,$sum);//獲取消息隊列中的值,最後一個參數爲隊列中的值 $sum = intval($sum) + $part; msg_send($msgQueue,MSG_TYPE,$sum);//發送每次計算的結果給消息隊列 } // 等待子進程執行結束 while (pcntl_waitpid(0, $status) != -1) { $status = pcntl_wexitstatus($status); $pid = posix_getpid(); echo "Child $status completed\n"; } //全部子進程結束後,再取出最後在隊列中的值,就是int數組的和 msg_receive($msgQueue,MSG_TYPE,$msgType,1024,$sum); echo $sum;//輸出120