PHP 多线程(pcntl_fork)

前提

安装php_pcntl扩展

主要函数

  1. pcntl_fork()函数执行的时候,会创建一个子进程。子进程会复制当前进程,也就是父进程的所有:数据,代码,还有状态。
  2. pcntl_waitpid ()可以获取子进程的状态码
    返回的值可以是-1,0或者 >0的值, 如果是-1, 表示子进程出错, 如果>0表示子进程已经退出且值是退出的子进程pid
  3. posix_kill 线程清理

代码样例

$pIds = [];
        foreach ($arrChunk as $hitList) {
            $pid = pcntl_fork(); //创建子进程
            if ($pid > 0) {
                $pIds[] = $pid;
            } elseif ($pid == 0) {
                $this->filterTask($hitList);
                exit(0);
            } else {
                Bd_Log::warning("Fork error");
            }
        }

        $curTime = time();
        $timeout = 7200;
        while (count($pIds) > 1) {
            foreach ($pIds as $key => $value) {
                $res = pcntl_waitpid($value, $status, WNOHANG);
                if ($res == -1 || $res > 0) {
                    unset($pIds[$key]);
                }
                // 超时杀进程
                if ((time() - $curTime) > $timeout) {
                    posix_kill($value, 9);
                }
            }
        }

你可能感兴趣的:(PHP 多线程(pcntl_fork))