PHP纤程返回空值

wqsoz72f  于 2023-03-11  发布在  PHP
关注(0)|答案(1)|浏览(149)

当运行下面的代码时,它返回空值。我使用纤程来运行代码,使用的PHP版本是8.2

<?php
  
$data=["A","B","C"];
$fibers = [];
foreach ($data as $val) {
    $fiber = new Fiber(function () use ($val): void {
        Fiber::suspend($val);
    });

    $fiber->start();
    $fibers[] = $fiber;
}

$results = [];
foreach ($fibers as $fiber) {

    $results[] = $fiber->resume();
}

print_r($results);
?>

预期输出

Array
(
    [0] =>"A" 
    [1] =>"B"
    [2] =>"C"
)

运行上述代码时,返回以下输出

Array
(
    [0] => 
    [1] => 
    [2] => 
)
nuypyhwy

nuypyhwy1#

$fiber->start();的调用消耗了您的$val。根据文档,start()的返回值是为第一个Fiber::suspend()调用指定的变量,或者如果函数返回,则返回null。resume()也是如此,因此您对start()的调用已经返回了$val,然后resume()没有任何剩余。
您想要的结果可以通过以下代码实现:

<?php
  
$data=["A","B","C"];
$fibers = [];
foreach ($data as $val) {
    $fiber = new Fiber(function () use ($val): void {
        Fiber::suspend();
        Fiber::suspend($val);
    });

    $fiber->start();
    $fibers[] = $fiber;
}

$results = [];
foreach ($fibers as $fiber) {
    $results[] = $fiber->resume();
}

print_r($results);
?>

这里有一个重写的建议,同时仍然使用光纤:

<?php
  
$data=["A","B","C"];
$fibers = [];

$callback = function ($val): string {
    Fiber::suspend();
    return $val;
};

foreach ($data as $val) {
    $fiber = new Fiber($callback);
    $fiber->start($val);
    $fibers[] = $fiber;
}

$results = [];
foreach ($fibers as $fiber) {
    $fiber->resume();
    $results[] = $fiber->getReturn();
}

print_r($results);
?>

相关问题