PHP 本身是單線程模型,但透過多進程、Shell 協作或 Web Server 並發特性,可實現「類多線程」的並行處理能力。本文對比三種主流方案:Shell 背景執行、pcntl_fork 多進程、HTTP 子請求,並提供生產級代碼範例與避坑指南。
利用 Shell & 將 PHP 腳本推至後台並行運行,適合獨立、無強依賴的批量任務(如郵件發送、報表生成、爬蟲)。
<?php
// 模擬耗時任務
$id = $argv[1] ?? uniqid();
$start = microtime(true);
sleep(rand(2, 5));
file_put_contents("/tmp/task_{$id}.log", "Task $id done in " . (microtime(true) - $start) . "s\n", FILE_APPEND);
?>
#!/bin/bash
for i in {1..10}; do
/usr/bin/php /var/www/task.php "$i" &
done
wait # 等待所有後台任務結束
echo "All tasks completed."
| 優點 | 缺點 |
|---|---|
| 零代碼侵入,任務腳本無需修改 | 進程數難以動態控制,易造成資源耗盡 |
| 天然隔離,單任務崩潰不影響其他 | 無法直接獲取返回值,需靠文件/資料庫/隊列通訊 |
| 可利用系統 cron/系統定時器調度 | Windows 環境需借助 WSL 或啟動器實現 |
使用 pcntl 擴展在單一 PHP 進程內 fork 子進程,共享代碼段但獨立內存空間,適合高併發、需精細控制的場景(如並行抓取、批量計算)。
<?php
declare(ticks = 1); // 確保信號處理生效
$urls = [
'https://httpbin.org/delay/2',
'https://httpbin.org/delay/3',
'https://httpbin.org/delay/1',
'https://httpbin.org/delay/4',
];
$maxProcesses = 3; // 最大並發數
$children = []; // 存儲子進程 PID
$results = []; // 共享結果(需 IPC,此處簡化為文件)
function fetchUrl($url, $index) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$content = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return "[$index] HTTP {$info['http_code']} " . strlen($content) . " bytes\n";
}
foreach ($urls as $i => $url) {
// 等待可用槽位
while (count($children) >= $maxProcesses) {
foreach ($children as $pid => $status) {
$res = pcntl_waitpid($pid, $status, WNOHANG);
if ($res > 0) {
unset($children[$pid]);
// 這裡可讀取子進程寫入的結果文件
}
}
usleep(100000); // 0.1s
}
$pid = pcntl_fork();
if ($pid === -1) {
die("fork 失敗\n");
} elseif ($pid === 0) {
// ========== 子進程 ==========
$result = fetchUrl($url, $i);
file_put_contents("/tmp/result_{$i}.txt", $result);
exit(0);
// ============================
} else {
// ========== 父進程 ==========
$children[$pid] = 0;
}
}
// 等待剩餘子進程
while ($children) {
foreach ($children as $pid => $status) {
$res = pcntl_waitpid($pid, $status, WNOHANG);
if ($res > 0) unset($children[$pid]);
}
usleep(100000);
}
echo "所有任務完成,結果文件在 /tmp/result_*.txt\n";
?>
declare(ticks=1) + pcntl_signal() 處理 SIGTERM/SIGCHLD,實現優雅關閉。pcntl_waitpid() 回收子進程,否則產生僵屍進程佔用 PID 表。主腳本通過 fsockopen、cURL 或 Guzzle 向同一台服務器發起非阻塞 HTTP 請求,利用 Nginx/Apache 的並發能力實現並行。適合已有 HTTP 介面、需復用現有控制器邏輯的場景。
<?php
$urls = [
'https://localhost/api/task/1',
'https://localhost/api/task/2',
'https://localhost/api/task/3',
];
$mh = curl_multi_init();
$handles = [];
foreach ($urls as $i => $url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HEADER => false,
]);
curl_multi_add_handle($mh, $ch);
$handles[$i] = $ch;
}
$running = null;
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh, 0.1); // 等待活動,避免佔用 CPU
} while ($running > 0);
$results = [];
foreach ($handles as $i => $ch) {
$results[$i] = curl_multi_getcontent($ch);
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
curl_multi_close($mh);
print_r($results);
?>
| 模式 | 實現方式 | 並發效果 | 適用場景 |
|---|---|---|---|
| 同步阻塞 | file_get_contents、curl_exec 循環 |
串行,總耗時 = Σ單任務耗時 | 任務少、耗時短、有強順序依賴 |
| 非阻塞 | curl_multi、stream_socket_client + stream_set_blocking(0) |
並行,總耗時 ≈ max(單任務耗時) | 任務多、IO 密集、無順序依賴 |
無論哪種方案,**多進程/線程寫入同一文件或資料庫記錄時必須加鎖**:
flock($fp, LOCK_EX) 獨佔寫入,LOCK_UN 釋放。SELECT ... FOR UPDATE、樂觀鎖(版本號)、或分布式鎖。| 場景 | 推薦方案 | 核心依賴 |
|---|---|---|
| 簡單定時批量任務 | Shell + cron | 系統 Shell |
| 高併發爬蟲、數據處理 | pcntl_fork / Swoole | pcntl 擴展 / Swoole |
| 復用現有 HTTP API | curl_multi / Guzzle Promise | cURL 擴展 |
| 分布式、跨語言、需持久化 | 消息佇列 + Worker 集群 | Redis / RabbitMQ / Kafka |