Swoole study notes-make a meal 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 problem in elementary school mathematics: "Arrange Time Reasonably", let's do a problem first:

 

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 sync()

    {

        $startTime = time();

 

        echo "Start making soup...". PHP_EOL;

        sleep(10);

        echo "The soup is ready...". PHP_EOL;

 

        echo "Start cooking...". PHP_EOL;

        sleep(8);

        echo "The rice is cooked...". PHP_EOL;

 

        echo "放油..." . PHP_EOL;

        sleep(1);

        echo "Fried fish...". PHP_EOL;

        sleep(3);

        echo "Put the salt...". PHP_EOL;

        sleep(1);

        echo "Out of the pot...". PHP_EOL;

 

        var_dump('Total time:'. (time()-$startTime).'minutes');

    }

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();

 

        // Turn on one-click coroutine: https://wiki.swoole.com/#/runtime?id=swoole_hook_all

        Swoole\Runtime::enableCoroutine($flags = SWOOLE_HOOK_ALL);

 

        // Create a coroutine container: https://wiki.swoole.com/#/coroutine/scheduler

        // Equivalent to entering the kitchen

        \Co\run(function () {

            // Wait for the result: https://wiki.swoole.com/#/coroutine/wait_group?id=waitgroup

            // Record which dish is ready and how long it will take which dish

            $wg = new WaitGroup();

            // The result of saving the data

            // Prepackaged dishes

            $result = [];

 

            // Record the soup (record a task)

            $wg->add();

            // Create a soup task (open a new coroutine)

            Coroutine::create(function () use ($wg, &$result) {

                echo "Start making soup...". PHP_EOL;

                // It takes 6 minutes to cook the soup, so we don’t have to wait here for the soup to cook,

                // Go directly to the next task: stir-fry (switching coroutines)

                sleep(8);

                echo "The soup is ready...". PHP_EOL;

 

                // install

                $result['soup'] ='A pot of soup';

                $wg->done(); // mark task completed

            });

 

            // Record cooking (record a task)

            $wg->add();

            // Create a cooking task (open a new coroutine)

            Coroutine::create(function () use ($wg, &$result) {

                echo "Start cooking...". PHP_EOL;

                // It takes 5 minutes to cook the rice, so we don’t have to wait here for the rice to be cooked, just leave it here for a while and check it out.

                // Let's go to the soup first (coroutine switch)

                sleep(10);

                echo "The rice is cooked...". PHP_EOL;

 

                // install

                $result['rice'] ='A pot of rice';

                $wg->done(); // mark task completed

            });

 

            // Record the cooking

            $wg->add();

            // Create a cooking task (start a new coroutine)

            Coroutine::create(function () use ($wg, &$result) {

                // The process of frying fish must be executed in a coroutine, if not, the fish may be out of the pot before it is fried

                // Because after starting the coroutine, the IO is all asynchronous. In this demo, the current coroutine will be suspended every time sleep is encountered

                // Switch to the next coroutine execution.

                // For example, if you start a new coroutine to execute the pan out step, the fish will be out of the pan when the fish is fried.

                echo "放油..." . PHP_EOL;

                sleep(1);

                echo "Fried fish...". PHP_EOL;

                sleep(3);

                echo "Put the salt...". PHP_EOL;

                sleep(1);

                echo "Out of the pot...". PHP_EOL;

 

                // install

                $result['food'] ='Shredded Pork with Fish Flavor';

                $wg->done();

            });

 

            // Wait for all tasks to complete

            $wg->wait();

 

            // Return data (Serve!)

            var_dump($result);

        });

 

        var_dump('Total time:'. (time()-$startTime).'minutes');

    }

}

Total time: 10 minutes

 

 

Guess you like

Origin blog.csdn.net/mjian178/article/details/113073031