ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# enable_coroutine 根据 [RFC1011](https://github.com/swoole/rfc-chinese/issues/24) 实现 > enable_coroutine 选项相当于在回调中关闭以前版本的SW_COROUTINE宏开关, 关闭时在回调事件中不再创建协程,但是保留用户创建协程的能力。 --- ### enable_coroutine选项影响范围 所有原有自动创建协程的回调, 包括 - onWorkerStart - onConnect - onOpen - onReceive - redis_onReceive - onHandShake - onPacket - onRequest - onMessage - onPipeMessage - onClose - tick/after 定时器 ## 4.0以下版本 `2.0-4.0`版本默认会在`Server`的回调函数中自动创建协程,如果在此事件中未使用任何协程`API`,实际上是浪费的。而且造成了与`1.x`的不兼容性。 此外还包括`Timer`定时器的相关`API`也会自动创建协程。 ## 简介 `enable_coroutine`参数,默认为`true`,通过设置为`false`可关闭内置协程。 ## 示例 ```php $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.x`是`100%`一致的 ## 效果 - 重新兼容了`1.x` - 开发者有更大的自由度 - 移除`--enable-coroutine`编译选项,减少`SW_USE_COROUTINE`宏开关的维护成本