带着问题出发
错误版本1
public function hello2(RequestInterface $request)
{
$name = '';
$channel = new \Swoole\Coroutine\Channel(12);
for ($i=0;$i<10;$i++){
co(function () use ($channel,$name){
$users = Db::select('select count(*) as ct from xxx;'); // 返回array
foreach($users as $user){
$name .= $user->ct;
}
});
// var_dump($channel->pop());
}
var_dump($name);
}
- 这样做是拿不到值的,因为协程是互相独立的所以压根就拿不到值参数的,而且主线程不会等协程,因此为空值,
正确姿势1(通过管道来实现)
public function hello1(RequestInterface $request)
{
$data = [];
$channel = new \Swoole\Coroutine\Channel(12);
for ($i=0;$i<10;$i++){
co(function () use ($channel){
$users = Db::select('select count(*) as ct from xxx;'); // 返回array
foreach($users as $user){
$channel->push($user->ct);
}
});
}
for ($i = 0; $i < 10; $i++)
{
// 当通道为空时,会自动挂起当前协程,等待生产者推送数据后,重新调度进来
$data [] = $channel->pop();
}
var_dump($channel->pop());
}
正确用法2(通过协程等待)
public function index2()
{
$channel = new \Swoole\Coroutine\Channel(10);
$wg = new \Swoole\Coroutine\WaitGroup();
$data = [];
$wg->add(10);
for ($i=0;$i<10;$i++){
co(function () use ($channel,$wg,&$data){
$users = Db::select('select count(*) as ct from t_lease_assets;'); // 返回array
foreach($users as $user){
$data[] = $user->ct;
}
$wg->done();
});
}
$wg->wait();
return $data;
}
https://www.cnblogs.com/danhuang/archive/2020/07/15/13277498.html //参考文章
- 放入通道中,然后再获取通道参数即可,这里注意要设定channel的个数否则拿不全参数