当前位置: 首页 > 后端技术 > PHP

MixPHPV2新特性:协程、定时器

时间:2023-03-29 15:42:05 PHP

协程MixPHPV2基于Swoole4的PHPStreamHook协程技术开发,协程的使用与Golang几乎相同,包括框架封装的协程池和连接池,命令行处理很多参考了Golang的系统库风格。除了没有selectcase,MixPHP和Golang的协程几乎没有区别,框架还提供了连接池、协程池、命令行处理等开箱即用的封装。xgo+Channelxgo类似于Golang的go关键字,可以启动一个新的协程。Channel相当于Golang的chan类,负责在不同的协程中传递数据。*/classCoroutineCommand{/***Mainfunction*/publicfunctionmain(){xgo(function(){$time=time();$chan=newChannel();for($i=0;$i<2;$i++){xgo([$this,'foo'],$chan);}for($i=0;$i<2;$i++){$result=$chan->pop();}println('总时间:'.(time()-$time));});事件::等待();}/***查询数据*@paramChannel$chan*/publicfunctionfoo(Channel$chan){$db=app()->dbPool->getConnection();$result=$db->createCommand('selectsleep(5)')->queryAll();$db->发布();//非手动释放的连接不会返回到连接池,$chan->push($result);在销毁过程中将被丢弃;}}执行结果是5s,说明WaitGroup+xdeferWaitGroup的并行执行和Golang完全一样,xdefer方法也相当于Golang的defer关键字。当并行执行不需要返回结果时,可以使用WaitGroup+xdefer,即使方法抛出异常,xdefer仍然会执行,可以避免一直阻塞。*/classWaitGroupCommand{/***Mainfunction*/publicfunctionmain(){xgo(function(){$wg=WaitGroup::new();for($i=0;$i<2;$i++){$wg->add(1);xgo([$this,'foo'],$wg);}$wg->wait();println('全部完成!');});事件::等待();}/***查询数据*@paramWaitGroup$wg*/publicfunctionfoo(WaitGroup$wg){xdefer(function()use($wg){$wg->done();});println('工作');抛出新的\RuntimeException('ERROR');}}即使抛出RuntimeException,它仍然可以执行到println('Alldone!');而不会导致wg中的chan一直被阻塞。在定时器异步编程中,定时器的使用非常频繁。Timer::new()可以获得一个实例。after方法可以设置一次性计时。tick方法可以设置一个连续的定时,停止当前的定时周期。你只需要$timer->clear();对象的方法。*/classTimerCommand{/***Mainfunction*/publicfunctionmain(){//一次性计时Timer::new()->after(1000,function(){println(time());});//连续计时$timer=newTimer();$timer->tick(1000,function(){println(time());});//停止计时Timer::new()->after(10000,function()use($timer){$timer->clear();});事件::等待();}}