Example and priority of spool coroutine

Time:2021-6-30

Example 1:

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; // Can be executed

Example 2:

Co\run(function () {
    $server = new Co\Http\Server("127.0.0.1", 9502, false);
    $server->handle('/', function ($request, $response) {
        $response->end("Index");
    });
    $server->start();
});
echo 1; // Can't execute

Example 3:

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

go(function() {
  //The code of the underlying subroutine is executed first
  go(function () {
      //The subprogram suspends and executes the upper code
      Co\System::sleep(3.0);
      go(function () {
          Co\System::sleep(2.0);
          echo "co[3] end\n";
      });
      echo "co[2] end\n";
  });

  //The coroutine is suspended, but no handoff is required
  Co\System::sleep(1.0);
  echo "co[1] end\n";
});

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

Example 4:

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

echo "main start\n";

Co\run(function () {
    echo "coro " . co::getcid() . " start\n";
    
    //Create and start a subprogram
    go(function () {
        echo "coro " . co::getcid() . " start\n";
        
        //When a coroutine scheduling occurs, go back to execute the outer coroutine
        Co\System::sleep(.2);
        echo "coro " . co::getcid() . " end\n";
    });
    
    echo "coro " . co::getcid() . " do not wait children coroutine\n";
    
    //There is a schedule, but the sub schedule is not finished, so continue to execute
    Co\System::sleep(.1);
    echo "coro " . co::getcid() . " end\n";
    //After executing the outer protocol, go back to execute the sub protocol
});
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
*/