ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
# Select多路选择器 ## 多路选择器的功能介绍 比如我们有ABCD四个任务,我们希望这4个任务并发的执行,最后谁返回的结果最快我们便选择那个结果,不等待其余任务的结果返回,不堵塞。 下面提供一个操作实例 ```php /** * select方法测试 * @return \Generator */ public function http_test_select() { yield $this->redis_pool->getCoroutine()->set('test', 1); $c1 = $this->redis_pool->getCoroutine()->get('test'); $c2 = $this->redis_pool->getCoroutine()->get('test1'); $result = yield SelectCoroutine::Select(function ($result) { if ($result != null) { return true; } return false; }, $c2, $c1); $this->http_output->end($result); } ``` Select函数原型 ```php function Select($matchFunc, CoroutineBase ...$coroutines) ``` SelectCoroutine::Select函数可以接受n个参数,第一个参数是匹配函数用于筛选,如果结果满足便返回true否则返回false,第二到n个参数为CoroutineBase。 上述代码将在c1,c2中选择一个最快速的非null的值。得到需要结果后不会继续等待其他的结果。 需要注意的是每个协程都有拥有超时限制,这里SelectCoroutine在超时时间内没有获得符合条件的结果将会报超时错误。