PHP多程式處理並行處理任務例項(轉,備用)

OldBoy~發表於2018-02-04

本文目的
本文通過例子講解linux環境下,使用php進行併發任務處理,以及如何通過pipe用於程式間的資料同步。
PHP多程式
通過pcntl_XXX系列函式使用多程式功能。注意:pcntl_XXX只能執行在php CLI(命令列)環境下,在web伺服器環境下,會出現無法預期的結果,請慎用!
管道PIPE
管道用於承載簡稱之間的通訊資料。為了方便理解,可以將管道比作檔案,程式A將資料寫到管道P中,然後程式B從管道P中讀取資料。php提供的管道操作API與操作檔案的API基本一樣,除了建立管道使用posix_mkfifo函式,讀寫等操作均與檔案操作函式相同。當然,你可以直接使用檔案模擬管道,但是那樣無法使用管道的特性了。
殭屍程式
子程式結束時,父程式沒有等待它(通過呼叫wait或者waitpid),那麼子程式結束後不會釋放所有資源(浪費呀!),這種程式被稱為殭屍程式,他裡面存放了子程式結束時的相關資料,如果殭屍程式過多,會佔用大量系統資源(如記憶體),影響機器效能。

程式碼

<?php

 
define("PC", 10); // 程式個數
define("TO", 4); // 超時
define("TS", 4); // 事件跨度,用於模擬任務延時
 
if (!function_exists('pcntl_fork')) {
    die("pcntl_fork not existing");
}
 
// 建立管道
$sPipePath = "my_pipe.".posix_getpid();
if (!posix_mkfifo($sPipePath, 0666)) {
    die("create pipe {$sPipePath} error");
}
 
// 模擬任務併發
for ($i = 0; $i < PC; ++$i ) {
    $nPID = pcntl_fork(); // 建立子程式
    if ($nPID == 0) {
        // 子程式過程
        sleep(rand(1,TS)); // 模擬延時
        $oW = fopen($sPipePath, 'w');
        fwrite($oW, $i."\n"); // 當前任務處理完比,在管道中寫入資料
        fclose($oW);
        exit(0); // 執行完後退出
    }
}
 
// 父程式
$oR = fopen($sPipePath, 'r');
stream_set_blocking($oR, FALSE); // 將管道設定為非堵塞,用於適應超時機制
$sData = ''; // 存放管道中的資料
$nLine = 0;
$nStart = time();
while ($nLine < PC && (time() - $nStart) < TO) {
    $sLine = fread($oR, 1024);
    if (empty($sLine)) {
        continue;   
    }   
     
    echo "current line: {$sLine}\n";
    // 用於分析多少任務處理完畢,通過‘\n’標識
    foreach(str_split($sLine) as $c) {
        if ("\n" == $c) {
            ++$nLine;
        }
    }
    $sData .= $sLine;
}
echo "Final line count:$nLine\n";
fclose($oR);
unlink($sPipePath); // 刪除管道,已經沒有作用了
 
// 等待子程式執行完畢,避免殭屍程式
$n = 0;
while ($n < PC) {
    $nStatus = -1;
    $nPID = pcntl_wait($nStatus, WNOHANG);
    if ($nPID > 0) {
        echo "{$nPID} exit\n";
        ++$n;
    }
}
 
// 驗證結果,主要檢視結果中是否每個任務都完成了
$arr2 = array();
foreach(explode("\n", $sData) as $i) {// trim all
    if (is_numeric(trim($i))) {
        array_push($arr2, $i);  
    }
}
$arr2 = array_unique($arr2);
if ( count($arr2) == PC) {  
    echo 'ok'; 
} else {
    echo  "error count " . count($arr2) . "\n";
    var_dump($arr2);
}
# time php fork.php 
current line: 1

current line: 3

current line: 4

current line: 5

current line: 8

Final line count:5
62732 exit
62734 exit
62735 exit
62736 exit
62739 exit
62740 exit
62731 exit
62737 exit
62738 exit
62733 exit
error count 5
array(5) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "3"
  [2]=>
  string(1) "4"
  [3]=>
  string(1) "5"
  [4]=>
  string(1) "8"
}

real    0m4.199s
user    0m1.840s
sys    0m1.554s

摘自:https://blog.csdn.net/u014511737/article/details/47003885

相關文章