• Swoole 协程使用示例及协程优先级


    示例一:

    Co::set(['hook_flags'=> SWOOLE_HOOK_ALL]);
    
    Co
    un(function () {
        go(function() {
            var_dump(file_get_contents("http://www.baidu.com/"));
        });
    
        go(function() {
            CoSystem::sleep(1);
            echo "done
    ";
        });
    });
    echo 1; //可以执行
    

    示例二:

    Co
    un(function () {
        $server = new CoHttpServer("127.0.0.1", 9502, false);
        $server->handle('/', function ($request, $response) {
            $response->end("<h1>Index</h1>");
        });
        $server->start();
    });
    echo 1; //不能执行
    

    示例三:

    Co::set(['hook_flags'=> SWOOLE_HOOK_ALL]);
    
    go(function() {
      // 底层优先执行子协程的代码
      go(function () {
          // 子协程挂起,执行上层代码
          CoSystem::sleep(3.0);
          go(function () {
              CoSystem::sleep(2.0);
              echo "co[3] end
    ";
          });
          echo "co[2] end
    ";
      });
    
      // 协程挂起,但不需要切换
      CoSystem::sleep(1.0);
      echo "co[1] end
    ";
    });
    
    /*
    co[1] end
    co[2] end
    co[3] end
    */
    

    示例四:

    Co::set(['hook_flags'=> SWOOLE_HOOK_ALL]);
    
    echo "main start
    ";
    
    Co
    un(function () {
        echo "coro " . co::getcid() . " start
    ";
        
        // 创建并开始执行子协程
        go(function () {
            echo "coro " . co::getcid() . " start
    ";
            
            // 发生协程调度,回去执行外层协程
            CoSystem::sleep(.2);
            echo "coro " . co::getcid() . " end
    ";
        });
        
        echo "coro " . co::getcid() . " do not wait children coroutine
    ";
        
        // 发生协程调度,但子协程还没执行完,继续往下执行
        CoSystem::sleep(.1);
        echo "coro " . co::getcid() . " end
    ";
        // 外层协程执行完毕,回去执行子协程
    });
    echo "end
    ";
    
    /*
    main start
    coro 1 start
    coro 2 start
    coro 1 do not wait children coroutine
    coro 1 end
    coro 2 end
    end
    */
    
  • 相关阅读:
    centos配置WordPress(Apache+mysql+php)
    sublime text3配置Python2、Python3的编译环境
    Python3——字典
    Python3基础——函数
    Python3基础——递归
    Python3基础——字符串类型
    activiti会签直接写死人员
    delete执行速度优化
    C盘空间满了怎么办
    python运算符
  • 原文地址:https://www.cnblogs.com/danhuang/p/13267457.html
Copyright © 2020-2023  润新知