zoukankan      html  css  js  c++  java
  • 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
    */
    
  • 相关阅读:
    autolayout先进的自动布局工具箱
    iOS7自定义back按钮和pop交互手势
    iOS7开发技巧
    UICollectionView专题
    关于AutoLayout(自动布局)那些事儿
    代码统计利器--CLOC
    vue之指令篇 ps简单的对比angular
    从无到有之webpack+vuerouter的简单例子以及各个属性解释
    关于requestanimationframe
    vim常用指令
  • 原文地址:https://www.cnblogs.com/danhuang/p/13267457.html
Copyright © 2011-2022 走看看