Coroutine

短名称

2.0.132.1.0或更高版本中,增加了协程短名特性,简化了协程相关API的名称书写。可修改php.ini设置swoole.use_shortname来关闭/开启短名,默认为开启。

创建协程

  1. go(function () {
  2. co::sleep(0.5);
  3. echo "hello";
  4. });
  5. go("test");
  6. go([$object, "method"]);

通道操作

  1. $c = new chan(1);
  2. $c->push($data);
  3. $c->pop();

协程客户端

  1. $redis = new Co\Redis;
  2. $mysql = new Co\MySQL;
  3. $http = new Co\Http\Client;
  4. $tcp = new Co\Client;
  5. $http2 = new Co\Http2\Client;

其他 API

  1. co::sleep(100);
  2. co::fread($fp);
  3. co::gethostbyname('www.baidu.com');

延迟执行

  1. defer(function () use ($db) {
  2. $db->close();
  3. });