PHP Swoole study notes-use the way of cooking to understand the coroutine

Introduction

Recently I learned about swoole and came into contact with coroutines, and recorded the coroutines I understood.
The article is relatively vernacular, and the current understanding is still very shallow, write your own thoughts, please give me some advice.

Coroutine

A coroutine can be simply understood as a thread, but this thread is in user mode and does not require the participation of the operating system. The cost of creating, destroying and switching is very low. Unlike threads, coroutines cannot use multi-core cpu, and want to use multi-core cpu. Need to rely on Swoole's multi-process model. —— Chapter of swoole coroutine

My understanding

You can think of Xiecheng as a topic in elementary school mathematics: "Arrange your time reasonably", let's first make a topic:

Xiao Ming goes home to cook rice after get off work. It takes 10 minutes to cook the soup, 8 minutes to cook the rice, and 5 minutes to cook. How long does it take Xiao Ming to cook the rice?

Now use sleep() to simulate IO operation

Synchronized cooking

public function async()
    {
    
    
        $startTime = time();

        echo "开始煲汤..." . PHP_EOL;
        sleep(10);
        echo "汤好了..." . PHP_EOL;

        echo "开始煮饭..." . PHP_EOL;
        sleep(8);
        echo "饭熟了..." . PHP_EOL;

        echo "放油..." . PHP_EOL;
        sleep(1);
        echo "煎鱼..." . PHP_EOL;
        sleep(3);
        echo "放盐..." . PHP_EOL;
        sleep(1);
        echo "出锅..." . PHP_EOL;

        var_dump('总耗时:' . (time() - $startTime) . ' 分钟');
    }

Total time: 23 minutes

The code is easy to understand. Wait for the soup to be cooked before cooking, and then wait for the rice to be cooked before cooking. This is not the case in life, right? It is necessary to introduce a coroutine to solve this problem.

Coroutine version of cooking

<?php
namespace Study\Co;

use Swoole\Coroutine;
use Swoole\Coroutine\WaitGroup;
use Swoole;

class co
{
    
    
    public function cookByCo()
    {
    
    
        $startTime = time();

        // 开启一键协程化: https://wiki.swoole.com/#/runtime?id=swoole_hook_all
        Swoole\Runtime::enableCoroutine($flags = SWOOLE_HOOK_ALL);

        // 创建一个协程容器: https://wiki.swoole.com/#/coroutine/scheduler
        // 相当于进入厨房
        \Co\run(function () {
    
    
            // 等待结果: https://wiki.swoole.com/#/coroutine/wait_group?id=waitgroup
            // 记录哪道菜做好了,哪道菜还需要多长时间
            $wg = new WaitGroup();
            // 保存数据的结果
            // 装好的菜
            $result = [];

            // 记录一下煲汤(记录一个任务)
            $wg->add();
            // 创建一个煲汤任务(开启一个新的协程)
            Coroutine::create(function () use ($wg, &$result) {
    
    
                echo "开始煲汤..." . PHP_EOL;
                // 煲汤需要6分钟,所以我们也不用在这里等汤煮好,
                // 直接去做下一个任务:炒菜(协程切换)
                sleep(8);
                echo "汤好了..." . PHP_EOL;

                // 装盘
                $result['soup'] = '一锅汤';
                $wg->done(); // 标记任务完成
            });

            // 记录一下煮饭(记录一个任务)
            $wg->add();
            // 创建一个煮饭任务(开启一个新的协程)
            Coroutine::create(function () use ($wg, &$result) {
    
    
                echo "开始煮饭..." . PHP_EOL;
                // 煮饭需要5分钟,所以我们不用在这里等饭煮熟,放在这里一会再来看看好了没有
                // 我们先去煲汤(协程切换)
                sleep(10);
                echo "饭熟了..." . PHP_EOL;

                // 装盘
                $result['rice'] = '一锅米饭';
                $wg->done(); // 标记任务完成
            });

            // 记录一下炒菜
            $wg->add();
            // 创建一个炒菜任务(再开启一个新的协程)
            Coroutine::create(function () use ($wg, &$result) {
    
    
                // 煎鱼的过程必须放在一个协程里面执行,如果不是的话可能鱼还没煎好就出锅了
                // 因为开启协程后,IO全是异步了,在此demo中每次遇到sleep都会挂起当前协程
                // 切换到下一个协程执行。
                // 例如把出锅这一步开启一个新协程执行,则在煎鱼的时候鱼,鱼就出锅了。
                echo "放油..." . PHP_EOL;
                sleep(1);
                echo "煎鱼..." . PHP_EOL;
                sleep(3);
                echo "放盐..." . PHP_EOL;
                sleep(1);
                echo "出锅..." . PHP_EOL;

                // 装盘
                $result['food'] = '鱼香肉丝';
                $wg->done();
            });

            // 等待全部任务完成
            $wg->wait();

            // 返回数据(上菜!)
            var_dump($result);
        });

        var_dump('总耗时:' . (time() - $startTime) . ' 分钟');
    }
}

Total time: 10 minutes

Answer: It takes at least 10 minutes for Xiao Ming to cook the rice.

Mainly referenced articles

www.easyswoole.com/Cn/NoobCourse/coroutine.html
hyperf.wiki/#/zh-cn/coroutine
wiki.swoole.com/#/coroutine

Pay attention, don't get lost

Alright, everyone, the above is the entire content of this article. The people who can see here are all talents . As I said before, there are a lot of technical points in PHP, because there are too many, it is really impossible to write, and you will not read too much after writing it, so I will organize it into PDF and documents here, if necessary Can

Click to enter the secret code: PHP+「Platform」

Insert picture description here

Insert picture description here


For more learning content, please visit the [Comparative Standard Factory] excellent PHP architect tutorial catalog, as long as you can read it to ensure that the salary will rise a step (continuous update)

The above content hopes to help everyone . Many PHPers always encounter some problems and bottlenecks when they are advanced. There is no sense of direction when writing too much business code. I don’t know where to start to improve. I have compiled some information about this, including But not limited to: distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripts, Docker, microservices, Nginx, etc. Many knowledge points, advanced advanced dry goods, can be shared with everyone for free, and those who need can join my PHP technology exchange group

Guess you like

Origin blog.csdn.net/weixin_49163826/article/details/109027754