Csp 并發(fā)模式
使用 子協(xié)程(go)
+ 通道(channel)
實(shí)現(xiàn) Csp
并發(fā)模式并發(fā)執(zhí)行。
當(dāng)我們需要并發(fā)執(zhí)行某些不相干的請(qǐng)求,并得到結(jié)果的時(shí)候,例如:
$sql1->exec();
$sql2->exec();
$sql2->exec();
在以上的代碼中,我們沒(méi)辦法最大的節(jié)約時(shí)間,因?yàn)?sql
語(yǔ)句都是順序執(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)然,在以上的代碼中,我們沒(méi)有充分地考慮超時(shí)等情況
進(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
方法提供了一個(gè)默認(rèn)參數(shù):超時(shí)時(shí)間(默認(rèn)為 5s
),當(dāng)調(diào)用 $csp->exec()
后,最長(zhǎng)等待 5s
左右會(huì)返回結(jié)果。如果你在 t2
函數(shù)中 co::sleep(6)
,那么 5s
后,返回的數(shù)據(jù)中不會(huì)包含 t2
函數(shù)的返回?cái)?shù)據(jù)。