jgswift / bubblr
异步协作任务调度器
0.1.5
2014-12-14 22:36 UTC
Requires
- php: >=5.5
- jgswift/observr: 0.2.*
- react/promise: 2.0.0
Requires (Dev)
- phpunit/phpunit: 3.7.*
This package is not auto-updated.
Last update: 2024-09-24 03:29:57 UTC
README
PHP 5.5+ 异步协作任务调度器
描述
bubblr 是一个轻量级组件,允许在不了解生成器或无需修改代码的情况下进行协作式多任务处理。bubblr 允许使用函数式和命令式编程范式进行多任务处理。
安装
使用 composer 通过命令行安装
php composer.phar require jgswift/bubblr:0.1.*
使用 composer.json 通过 composer 安装
{ "require": { "jgswift/bubblr": "0.1.*" } }
依赖
- php 5.5+
- jgswift/observr
- react/promise
用法
协程(Bubble)
协程,或称为 Bubbles(在这个包中如此称呼),是排队并执行的工作单元。任何函数或方法都可以被协程包装,以便轻松地进行多任务处理,并最小化开销。
BubbleInterface(缩写)
interface BubbleInterface extends EventInterface, EventAwareInterface { public function getResult(); public function setContext($context); public function resume(SpoutInterface $spout); public function suspend(SpoutInterface $spout); }
Spouts
Spouts 作为调度队列处理协程执行。
这在概念上类似于线程,但必须区分开来,因为协程是按顺序执行的。协程可以将执行优先级交还给 Spout,从而允许其他任务执行。有关更多信息,请参阅 Nikita Popov 撰写的 关于 PHP 中协作式多任务处理的相当全面的介绍。
SpoutInterface(缩写)
interface SpoutInterface extends BubblerAwareInterface { public function push(BubbleInterface $bubble); public function pop(); public function invoke(BubbleInterface $bubble); public function suspend(); public function resume(); }
核心 Bubbler
核心 Bubbler 是处理 Spout 创建和调度的主要应用程序。
协程、Spout 和核心都可以使用全局别名 API 进行修改。
BubblerInterface(缩写)
interface BubblerInterface { public function execute($bubble = null); public function attach(SpoutInterface $spout); public function detach(SpoutInterface $spout); public function resume(); public function suspend(); public function getSpout(); }
简单示例(返回值)
$hello = bubblr\async(function() { return 'hello world'; }); echo $hello(); // 'hello world'
调度现有方法
function hello() { return 'hello world'; } $hello = bubblr\async('hello'); echo $hello(); // 'hello world'
在长时间运行的任务中重新调度
$fib = bubblr\async(function($num) { $n1 = 0; $n2 = 1; $n3 = 1; for ($i = 2; $i < $num; ++$i) { $n3 = $n1 + $n2; $n1 = $n2; $n2 = $n3; // every 50 iterations this bubble will suspend and allow other waiting bubbles to execute if (!($i % 50)) { bubblr\reschedule(); } } return $n3; }); echo is_infinite($fib(3000)); // true
一次性调度多个协程
function hello() { return 'hello'; } function world() { return 'world'; } $results = bubblr\asyncAll([ 'hello', 'world' ]); var_dump($results); // Array ['hello','world']
抛出和处理异常
$addition = bubblr\async(function($a,$b) { if(!is_numeric($a) || !is_numeric($b)) { throw new \InvalidArgumentException(); } return $a + $b; }); try { $addition('bar',5); } catch(\InvalidArgumentException $e) { echo 'Invalid argument'; }