Home > Backend Development > PHP8 > body text

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

藏色散人
Release: 2023-02-17 12:30:02
forward
4047 people have browsed it

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;
    }
}
Copy after login
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
Copy after login

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();
    }
}
Copy after login
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
Copy after login

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;
}
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!