Csp 并發(fā)模式
使用 子協(xié)程(go)
+ 通道(channel)
實(shí)現(xiàn) Csp
并發(fā)模式并發(fā)執(zhí)行。
當(dāng)我們需要并發(fā)執(zhí)行某些不相干的請求,并得到結(jié)果的時候,例如:
$sql1->exec();
$sql2->exec();
$sql2->exec();
在以上的代碼中,我們沒辦法最大的節(jié)約時間,因為 sql
語句都是順序執(zhí)行的,因此我們引入了 Csp
并發(fā)編程的概念。
示例代碼
<?php
go(function () {
$channel = new \Swoole\Coroutine\Channel();
go(function () use ($channel) {
// 模擬執(zhí)行sql
\co::sleep(0.1);
$channel->push(1);
});
go(function () use ($channel) {
// 模擬執(zhí)行sql
\co::sleep(0.1);
$channel->push(2);
});
go(function () use ($channel) {
// 模擬執(zhí)行sql
\co::sleep(0.1);
$channel->push(3);
});
$i = 3;
while ($i--) {
var_dump($channel->pop());
}
});
當(dāng)然,在以上的代碼中,我們沒有充分地考慮超時等情況
進(jìn)一步封裝
<?php
go(function () {
$csp = new \EasySwoole\Component\Csp();
$csp->add('t1', function () {
\co::sleep(0.1);
return 't1 result';
});
$csp->add('t2', function () {
\co::sleep(0.1);
return 't2 result';
});
var_dump($csp->exec());
});
exec
方法提供了一個默認(rèn)參數(shù):超時時間(默認(rèn)為 5s
),當(dāng)調(diào)用 $csp->exec()
后,最長等待 5s
左右會返回結(jié)果。如果你在 t2
函數(shù)中 co::sleep(6)
,那么 5s
后,返回的數(shù)據(jù)中不會包含 t2
函數(shù)的返回數(shù)據(jù)。