Home  >  Article  >  Backend Development  >  PHP8.1 Fiber cross-executes multi-tasking (with detailed code explanation)

PHP8.1 Fiber cross-executes multi-tasking (with detailed code explanation)

藏色散人
藏色散人forward
2021-12-20 10:49:394079browse

Everyone’s computer should have at least 2 cores, but most of the programs running on our computers at the same time are far more than the number of cores of the CPU. This is because the operating system adopts a macro-parallel and micro-serial approach in task processing. That is, the CPU executes each program for a little while and then switches to execute other programs. It makes everyone seem to have performed a lot. Now php8.1. Introduced fiber. The scheduling rights are given to all PHP developers. So what new operations can we implement with fiber? (This article is a tip for everyone, and you are welcome to add more interesting uses)

Take the for loop that everyone usually writes as an example. Like go, you can write two go and write a loop in each to input at the same time. You can see that the output is alternate. In past PHP versions, if you only opened one cli and wrote multiple for loops, then its output must be sequential. Cross output cannot be achieved (that is, after executing several times in the first loop, b can be executed again, and b can be executed for a period of time, and then A can be executed).

Now with the help of fiber we can also achieve this operation. [Recommended learning: PHP video tutorial]

The following code can achieve two loops of cross execution. You can even control the execution frequency of two programs (for example, A is executed 3 times, and B is executed once)

<?php
$t1    = false;
$t2    = false;
$reg   = [];
$reg[] = new \Fiber(function () use (&$t1) {
    for ($i = 1; $i < 10; $i++) {
        echo $i;
        echo PHP_EOL;
        \Fiber::suspend();

    }
    $t1 = true;
});


$reg[] = new \Fiber(function () use (&$t2) {
    for ($i = 1; $i < 10; $i++) {
        echo $i;
        echo PHP_EOL;
        \Fiber::suspend();
    }
    $t2 = true;
});

$startTag = true;
while (count($reg) > 1) {

    if ($startTag) foreach ($reg as $pI) {
        $pI->start();
        $startTag = false;
    }

    foreach ($reg as $pI) {
        $pI->resume();
    }

    if ($t1 === true && $t2 === true) {
        break;
    }
}
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9

You can even control the execution frequency of two loops, for example, after the first loop is executed 3 times, The second loop is executed once. The code is as follows

<?php
$reg = [];
$fId = 1;


$reg[$fId] = new \Fiber(function () use (&$reg, $fId) {
    for ($i = 1; $i < 10; $i++) {
        echo $fId . &#39;:&#39; . $i;
        echo PHP_EOL;
        if ($i % 3 == 0) {
            \Fiber::suspend();
        }
    }
    unset($reg[$fId]);
});
$fId++;

$reg[$fId] = new \Fiber(function () use (&$reg, $fId) {
    for ($i = 1; $i < 10; $i++) {
        echo $fId . &#39;:&#39; . $i;
        echo PHP_EOL;
        \Fiber::suspend();
    }
    unset($reg[$fId]);
});

$startTag = true;
while (count($reg) > 0) {
    if ($startTag) foreach ($reg as $pI) {
        $pI->start();
        $startTag = false;
    }
    foreach ($reg as $pI) {
        $pI->resume();
    }
}
1:1
1:2
1:3
2:1
1:4
1:5
1:6
2:2
1:7
1:8
1:9
2:3
2:4
2:5
2:6
2:7
2:8
2:9

Complete through message notification

<?php

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: &#39;Sname&#39;,
    description: &#39;Add a short description for your command&#39;,
)]
class SnameCommand extends Command
{
    protected function configure(): void
    {
        $this
            ->addArgument(&#39;arg1&#39;, InputArgument::OPTIONAL, &#39;Argument description&#39;)
            ->addOption(&#39;option1&#39;, null, InputOption::VALUE_NONE, &#39;Option description&#39;);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $t1  = false;
        $t2  = false;
        $reg = [];
        $fId = 1;


        $reg[] = new \Fiber(function () use ($fId) {
            for ($i = 1; $i < 10; $i++) {
                echo $fId . &#39;:&#39; . $i;
                echo PHP_EOL;
                if ($i % 3 == 0) {
                    \Fiber::suspend(new SuspendData(Status::Running));
                }
            }
            \Fiber::suspend(new SuspendData(Status::Stop));

        });
        $fId++;

        $reg[] = new \Fiber(function () use ($fId) {
            for ($i = 1; $i < 10; $i++) {
                echo $fId . &#39;:&#39; . $i;
                echo PHP_EOL;
                \Fiber::suspend(new SuspendData(Status::Running));
            }
            \Fiber::suspend(new SuspendData(Status::Stop));
        });

        $startTag = true;
        while (count($reg) > 0) {
            if ($startTag) foreach ($reg as $pI) {
                $pI->start();
                $startTag = false;
            }
            foreach ($reg as $key => $pI) {
                $r = $pI->resume();
                if ($r->status === Status::Stop) {
                  unset($reg[$key]);
                }
            }
        }


        return Command::SUCCESS;
    }
}

class SuspendData
{
    public readonly Status $status;

    public function __construct($status)
    {
        $this->status = $status;
    }
}

enum Status
{
    case Stop;
    case Running;
}

The above is the detailed content of PHP8.1 Fiber cross-executes multi-tasking (with detailed code explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete