使用 pcntl_fork 实现多进程并行处理,配合共享内存或临时文件队列传递图片路径,避免 PHP-FPM 的线程阻塞。

并发模型与任务分发
PHP 原生不支持多线程,但 Linux 环境下可通过 fork 创建子进程。将待处理的图片列表加载到内存数组中,按 CPU 核心数拆分为多个批次,每个子进程独立执行 OCR 识别并写入结果。

主进程负责读取配置和拆分任务,子进程通过管道或信号量同步状态。这种方式能充分利用多核 CPU,显著降低批量处理的总耗时。需注意子进程的内存隔离,防止大图片数据在进程间意外共享导致 OOM。
OCR引擎调用与资源管理
在子进程中实例化 OCR SDK 或调用命令行工具(如 Tesseract),设置合理的超时时间和重试机制,确保单个任务失败不影响整体流程。

<?php
// batch_ocr.php
// 运行方式: php batch_ocr.php image_list.txt results.json
// 依赖: ext-pcntl, ext-posix
if (!extension_loaded('pcntl')) {
die("PCNTL extension required\n");
}
$imageListFile = $argv[1] ?? null;
$resultFile = $argv[2] ?? 'results.json';
if (!$imageListFile || !file_exists($imageListFile)) {
die("Usage: php batch_ocr.php <image_list.txt> [results.json]\n");
}
$images = array_filter(array_map('trim', file($imageListFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)));
if (empty($images)) {
die("No images to process\n");
}
$numProcesses = 4; // 根据CPU核心数调整
$chunks = array_chunk($images, ceil(count($images) / $numProcesses));
$pids = [];
foreach ($chunks as $index => $chunk) {
$pid = pcntl_fork();
if ($pid == -1) {
die("Fork failed\n");
} elseif ($pid == 0) {
// Child process
processChunk($chunk, "child_result_${index}.json");
exit(0);
} else {
$pids[] = $pid;
}
}
// Parent waits for all children
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
// Merge results
$results = [];
for ($i = 0; $i < count($chunks); $i++) {
$tempFile = "child_result_${i}.json";
if (file_exists($tempFile)) {
$results = array_merge($results, json_decode(file_get_contents($tempFile), true));
unlink($tempFile);
}
}
file_put_contents($resultFile, json_encode($results, JSON_PRETTY_PRINT));
echo "Processing complete. Results saved to {$resultFile}\n";
function processChunk($images, $outputFile) {
$results = [];
foreach ($images as $imgPath) {
if (!file_exists($imgPath)) {
$results[$imgPath] = ['error' => 'File not found'];
continue;
}
// Simulate OCR call
$text = simulateOcr($imgPath);
$results[$imgPath] = ['text' => $text];
}
file_put_contents($outputFile, json_encode($results));
}
function simulateOcr($path) {
// Replace with actual OCR SDK call
return "OCR result for " . basename($path);
}
程序接收图片路径列表文件,按指定进程数拆分任务。每个子进程独立处理一批图片,生成临时结果文件。主进程等待所有子进程结束后合并结果并保存为 JSON。若某张图片不存在,记录错误信息。实际使用时需替换 simulateOcr 为真实 OCR 调用逻辑。
每次识别完成后立即释放 OCR 引擎占用的显存或内存,避免累积泄漏。对于高频调用的场景,可复用 OCR 客户端连接而非每次新建。
异常处理与日志追踪
捕获子进程中的识别异常,记录失败图片的路径和错误码,支持断点续传和人工复核。
通过结构化日志(JSON 格式)输出每张图片的处理状态,便于后续分析瓶颈。结合 Redis 或数据库记录任务进度,实现可视化监控。