php中的并行函数调用

问题描述 投票:0回答:1

有没有办法在 PHP 中并行执行内部函数?

比如我有四个函数:

function a(){
    return 1;
}

function b(){
    return 2;
}

function c(){
    return 3;
}

function d(){
    return 4;
}

当我像这样依次调用这些函数时:

function E(){
    $response = [] ;
    $response['a'] = a();
    $response['b'] = b();
    $response['c'] = c();
    $response['d'] = d();
}

它们按顺序执行。但是,我想并行地调用它们。 PHP 有什么办法可以实现这一点吗?

我尝试使用 AMP 和 swoole php 但没有成功

php parallel-processing swoole amphp asynchronous-messaging-protocol
1个回答
0
投票
<?php

use Swoole\Coroutine;

function a()
{
    echo 1;
    sleep(1);
    echo __FUNCTION__;
}

function b()
{
    echo 2;
    sleep(1);
    echo __FUNCTION__;
}

function c()
{
    echo 3;
    sleep(1);
    echo __FUNCTION__;
}

function d()
{
    echo 4;
    sleep(1);
    echo __FUNCTION__;
}

Coroutine\run(function () {
    Coroutine::create('a');
    Coroutine::create('b');
    Coroutine::create('c');
    Coroutine::create('d');
});
© www.soinside.com 2019 - 2024. All rights reserved.