Open twn39 opened 5 years ago
使用方式:
go(function () {
$fetchWeb = function () {
return file_get_contents('http://www.baidu.com/');
};
$list = [
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
$fetchWeb,
];
$gw = new GroupWait($list);
$result = $gw->wait();
var_dump($result);
});
这里用了file_get_contents
,所以需要在头部加上: Swoole\Runtime::enableCoroutine();
<?php
use Swoole\Coroutine as Co;
class Group
{
private $channel;
private $items = [];
private $count;
public function __construct()
{
$this->channel = new Swoole\Coroutine\Channel();
}
public function add(callable $cor)
{
$this->items[] = $cor;
}
public function run()
{
$this->count = count($this->items);
foreach ($this->items as $item) {
go(function () use ($item) {
$item();
$this->channel->push(true);
});
}
while ($this->count --) {
$this->channel->pop();
}
}
}
go(function () {
$g = new Group();
$g->add(function () {
Co::sleep(5);
echo time();
echo "sleep: 5\r\n";
});
$g->add(function () {
Co::sleep(3);
echo time();
echo "sleep: 3\r\n";
});
$g->add(function () {
Co::sleep(8);
echo time();
echo "sleep: 8\r\n";
});
$g->run();
});
多个协程并行,类似于nodejs的Promise.all()。