× 警告!旧版文档已经暂停维护,请查看新版文档。点击前往新版文档

enable_coroutine

根据 RFC1011 实现

enable_coroutine 选项相当于在回调中关闭以前版本的SW_COROUTINE宏开关, 关闭时在回调事件中不再创建协程,但是保留用户创建协程的能力。

配置方法

  1. php.ini配置 swoole.enable_coroutine = 'Off' (推荐, 可见 ini配置文档 )
  2. $server->set(['enable_coroutine' => false]);
  3. swoole_async_set(['enable_coroutine' => false]);

enable_coroutine选项影响范围

所有原有自动创建协程的回调, 包括

  • onWorkerStart
  • onConnect
  • onOpen
  • onReceive
  • redis_onReceive
  • onPacket
  • onRequest
  • onMessage
  • onPipeMessage
  • onFinish
  • onClose
  • tick/after 定时器

4.0 以下版本

2.0-4.0版本默认会在Server的回调函数中自动创建协程,如果在此事件中未使用任何协程API,实际上是浪费的。而且造成了与1.x的不兼容性。

此外还包括Timer定时器的相关API也会自动创建协程。

简介

enable_coroutine参数,默认为true,通过设置为false可关闭内置协程。

示例

$http = new Swoole\Http\Server("127.0.0.1", 9501);

$http->set([
    //关闭内置协程
    'enable_coroutine' => false,
]);

$http->on("request", function ($request, $response) {
    if ($request->server['request_uri'] == '/coro') {
        go(function () use ($response) {
            co::sleep(0.2);
            $response->header("Content-Type", "text/plain");
            $response->end("Hello World\n");
        });
    } else {
        $response->header("Content-Type", "text/plain");
        $response->end("Hello World\n");
    }
});

$http->start();
  • enable_coroutine设置为true时,底层自动在onRequest回调中创建协程,开发者无需自行使用go函数创建协程
  • enable_coroutine设置为false时,底层不会自动创建协程,开发者如果要使用协程,必须使用go自行创建协程,如果不需要使用协程特性,则处理方式与1.x100%一致的

效果

  • 重新兼容了1.x
  • 开发者有更大的自由度
  • 移除--enable-coroutine编译选项,减少SW_USE_COROUTINE宏开关的维护成本