swoole中协程的学习,建立协程环境,以及协程异步理解
< 返回列表时间: 2020-05-25来源:OSCHINA
Swoole \Coroutine:: create ( function (){ echo "s1" . time (). PHP_EOL ; for ( $i = 0 ; $i < 100000000 ; $i ++){ $a = 2 ; } echo "e1" . time (). PHP_EOL ; }); Co :: create ( function (){ }); go( function (){ echo "s2" . time (). PHP_EOL ; for ( $i = 0 ; $i < 100000000 ; $i ++){ $a = 2 ; } echo "e2" . time (). PHP_EOL ; });
以上都是协程环境创建的方式。
sleep与Co::sleep的差别 Swoole\Coroutine:: create ( function (){ echo "g1:" . time (). PHP_EOL ; sleep ( 2 ); echo 'go1' . PHP_EOL ; }); go( function (){ echo "g2:" . time (). PHP_EOL ; sleep ( 3 ); echo 'go2' . PHP_EOL ; }); go( function (){ echo "g3:" . time (). PHP_EOL ; sleep ( 2 ); echo 'go3' . PHP_EOL ; });
依然按照顺序执行,结果为:
g1:1590400552
go1
g2:1590400554
go2
g3:1590400557
go3 Swoole\Coroutine:: create ( function (){ echo "g1:" . time (). PHP_EOL ; Co:: sleep ( 2 ); echo 'go1' . PHP_EOL ; }); go( function (){ echo "g2:" . time (). PHP_EOL ; Co:: sleep ( 3 ); echo 'go2' . PHP_EOL ; }); go( function (){ echo "g3:" . time (). PHP_EOL ; Co:: sleep ( 2 ); echo 'go3' . PHP_EOL ; });
结果为:
g1:1590400870
g2:1590400870
g3:1590400870
go1
go3
go2
说明sleep睡眠的是整个进程,Co::sleep睡眠对应协程
协程异步支持IO操作,但是直接的内存计算消费是不会被异步的 Swoole\Coroutine:: create ( function (){ echo "s1" . time (). PHP_EOL ; for ( $i = 0 ; $i < 100000000 ; $i ++){ $a = 2 ; } echo "e1" . time (). PHP_EOL ; }); go( function (){ echo "s2" . time (). PHP_EOL ; for ( $i = 0 ; $i < 100000000 ; $i ++){ $a = 2 ; } echo "e2" . time (). PHP_EOL ; }); go( function (){ echo "s3" . time (). PHP_EOL ; for ( $i = 0 ; $i < 100000000 ; $i ++){ $a = 2 ; } echo "e3" . time (). PHP_EOL ; });
结果为:
s11590400606
e11590400608
s21590400608
e21590400610
s31590400610
e31590400612
热门排行