Skip to content
This repository has been archived by the owner on Sep 1, 2020. It is now read-only.

Latest commit

 

History

History
67 lines (49 loc) · 1.98 KB

2.3.51 - enable_coroutine.md

File metadata and controls

67 lines (49 loc) · 1.98 KB

enable_coroutine

根据 RFC1011 实现

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


enable_coroutine选项影响范围

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

  • onWorkerStart
  • onConnect
  • onOpen
  • onReceive
  • redis_onReceive
  • onPacket
  • onRequest
  • onMessage
  • onPipeMessage
  • 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宏开关的维护成本