ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
[TOC] ## 概述 ``` 协程是并发执行的 ``` ## 简单 demo ``` public function index(){ for ($i=0; $i < 10; $i++) { go(function () use ($i){ echo "go ".$i; \co::sleep(3);//在协程中 sleep,不影响主进程 //sleep(3); // 影响住进程,3 秒后执行下一个协程 }); } $this->writeJson(200,"ok"); } ``` ## 处理上下文 ``` public function index(){ go(function (){ ContextManager::getInstance()->set('key','key in parent'); go(function (){ ContextManager::getInstance()->set('key','key in sub'); var_dump(ContextManager::getInstance()->get('key')." in"); }); \co::sleep(5);//不在主进程 sleep ,返回结果不会 sleep var_dump(ContextManager::getInstance()->get('key')." out"); }); /** * string(13) "key in sub in" string(17) "key in parent out" */ $this->writeJson(200,"ok"); } ``` ## WaitGroup ``` go(function (){ $ret = []; $wait = new \EasySwoole\Component\WaitGroup(); $wait->add(); go(function ()use($wait,&$ret){ \co::sleep(0.1); $ret[] = time(); $wait->done(); }); $wait->add(); go(function ()use($wait,&$ret){ \co::sleep(2); $ret[] = time(); $wait->done(); }); $wait->wait(); var_dump($ret); }); ``` [TOC]