PHP 다중 프로세스 처리 작업 살펴보기

coldplay.xixi
풀어 주다: 2023-04-09 15:44:01
앞으로
4584명이 탐색했습니다.

PHP 다중 프로세스 처리 작업 살펴보기

pcntl 모듈(Unix가 아닌 시스템은 이 모듈을 지원하지 않음)

pcntl 模块(非 Unix 类系统不支持此模块)

一个 PHP 多进程简单例子大概是这个样子:

// 5 个子进程处理任务for ($i = 0; $i < 5; $i++) {
    $pid = pcntl_fork();    if ($pid == -1) {        die("could not fork");
    } elseif ($pid) {        echo "I&#39;m the Parent $i\n";
    } else { // 子进程处理
        echo "I&#39;m the Child $i\n";        // 业务处理
        exit($i); // 一定要注意退出子进程,否则 pcntl_fork() 会被子进程再 fork,带来处理上的影响。
    }
}// 等待子进程执行结束while (pcntl_waitpid(0, $status) != -1) {
    $status = pcntl_wexitstatus($status);    echo "Child $status completed\n";
}复制代码
로그인 후 복사

当然实际应用中我们不能够这样输出代码,不够健壮,也不够优雅,我所以找了个基于 pcntl 封装的扩展包来使用。

spatie/async - 基于 pcntl 封装的扩展包

以下是我使用 spatie/asyncPHP 다중 프로세스의 간단한 예는 아마도 다음과 같습니다:

/**
 * @param string $keyword
 *
 * @return array
 */public function searchAll(string $keyword): array{
    $songAll = [];    foreach ($this->platforms as $platform) {
        $songAll = array_merge($songAll, $this->search($platform, $keyword));
    }    return $songAll;
}/**
 * @param string $platform
 * @param string $keyword
 *
 * @return mixed
 */public function search(string $platform, string $keyword){
    $meting = $this->getMeting($platform);

    $songs = json_decode($meting->format()->search($keyword), true);    foreach ($songs as $key => &$song) {
        $detail = json_decode($meting->format()->url($song[&#39;url_id&#39;]), true);        if (empty($detail[&#39;url&#39;])) {            unset($songs[$key]);
        }
        $song = array_merge($song, $detail);
    }    unset($song);    return $songs;
}复制代码
로그인 후 복사

물론 우리는 할 수 없습니다 실제 애플리케이션에서는 출력 코드가 충분히 강력하지도, 우아하지도 않아서 pcntl 패키지 기반의 확장 패키지를 찾아서 사용했습니다.

spatie/async - pcntl 패키지를 기반으로 한 확장 패키지

다음은 제가 spatie/async 다중 프로세스 요청 최적화 예시PHP 다중 프로세스 처리 작업 살펴보기

원본 코드(약 20초 소요) - github.com/guanguans/m…

PHP 다중 프로세스 처리 작업 살펴보기

/**
 * @param string $keyword
 *
 * @return array
 */public function searchAll(string $keyword): array{
    $songAll = [];
    $pool = Pool::create();    foreach ($this->platforms as $platform) {
        $pool->add(function () use ($platform, $keyword) {            return $this->search($platform, $keyword);
        }, $this->getSerializedOutput())->then(function ($output) use (&$songAll) {
            $songAll = array_merge($songAll, $output);
        })->catch(function (\Throwable $exception) {            exit($exception->getMessage());
        });
    }
    $pool->wait();    return $songAll;
}/**
 * @return mixed
 */public function search(string $platform, string $keyword){
    $meting = $this->getMeting($platform);
    $songs = json_decode($meting->format()->search($keyword), true);

    $pool = Pool::create();    foreach ($songs as $key => &$song) {
        $pool->add(function () use ($meting, $song) {            return json_decode($meting->format()->url($song[&#39;url_id&#39;]), true);
        })->then(function ($output) use (&$songs, &$song, $key) {
            $song = array_merge($song, $output);            if (empty($song[&#39;url&#39;])) {                unset($songs[$key]);
            }
        })->catch(function (\Throwable $exception) {            exit($exception->getMessage());
        });
    }    unset($song);
    $pool->wait();    return $songs;
}复制代码
로그인 후 복사
개선 후(약 4초 소요) - github.com/guanguans/m…

rrreee프로그래밍에 대해 더 자세히 알고 싶다면 php training

칼럼을 주목해주세요! 🎜🎜🎜🎜

위 내용은 PHP 다중 프로세스 처리 작업 살펴보기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:juejin.im
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!