代码改变世界

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

2020-07-09 19:08  小伍2013  阅读(751)  评论(0编辑  收藏  举报

示例一:

Co::set(['hook_flags'=> SWOOLE_HOOK_ALL]);

Co\run(function () {
    go(function() {
        var_dump(file_get_contents("http://www.baidu.com/"));
    });

    go(function() {
        Co\System::sleep(1);
        echo "done\n";
    });
});
echo 1; //可以执行

示例二:

Co\run(function () {
    $server = new Co\Http\Server("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 () {
      // 子协程挂起,执行上层代码
      Co\System::sleep(3.0);
      go(function () {
          Co\System::sleep(2.0);
          echo "co[3] end\n";
      });
      echo "co[2] end\n";
  });

  // 协程挂起,但不需要切换
  Co\System::sleep(1.0);
  echo "co[1] end\n";
});

/*
co[1] end
co[2] end
co[3] end
*/

示例四:

Co::set(['hook_flags'=> SWOOLE_HOOK_ALL]);

echo "main start\n";

Co\run(function () {
    echo "coro " . co::getcid() . " start\n";
    
    // 创建并开始执行子协程
    go(function () {
        echo "coro " . co::getcid() . " start\n";
        
        // 发生协程调度,回去执行外层协程
        Co\System::sleep(.2);
        echo "coro " . co::getcid() . " end\n";
    });
    
    echo "coro " . co::getcid() . " do not wait children coroutine\n";
    
    // 发生协程调度,但子协程还没执行完,继续往下执行
    Co\System::sleep(.1);
    echo "coro " . co::getcid() . " end\n";
    // 外层协程执行完毕,回去执行子协程
});
echo "end\n";

/*
main start
coro 1 start
coro 2 start
coro 1 do not wait children coroutine
coro 1 end
coro 2 end
end
*/