liuggio / spawn
轻松实现 PHP 中闭包和命令的并发处理。
dev-master
2016-07-15 10:56 UTC
Requires
- jeremeamia/superclosure: ^2.1
- symfony/event-dispatcher: ^2.7
- symfony/process: ^2.2
- symfony/stopwatch: ^2.2
Requires (Dev)
- phpunit/phpunit: ^4
This package is auto-updated.
Last update: 2024-09-18 22:32:05 UTC
README
Spawn 的主要任务是提高并发进程的性能处理。
这个库尽可能地利用机器的所有核心来加速处理,这在需要运行大量命令时很有用,例如:单元测试/功能测试/CS 修复/文件处理。
$spawn = new Spawn(); $spawn ->processes(range(1,10), "printenv > '/tmp/envs_{}{p}.log';") ->onCompleted(function(Process $singleProcess){ /* print stats */}); ->start();
并发 \Closure?真的吗?
是的!使用这个库,你可以使用并发的闭包,但是PHP 不是 Go-lang
,也不是 Erlang
或其他任何著名的并发语言,为了模拟独立的例程,闭包被序列化并在新的 PhpProcess 中执行,请注意,这是一个加快并发闭包速度的解决方案。
使用这个库,你还可以
- 执行并处理 并发 PHP 闭包。
- 创建一个独立的进程来执行单个闭包。
并发闭包:上传图片到你的 CDN
提供一个迭代器,它将任务分割成多个 PHP 脚本并在多个进程中分配。为了提高性能,进程的数量等于计算机的核心数。
$spawn = new Spawn(); $files = new RecursiveDirectoryIterator('/path/to/images'); $files = new RecursiveIteratorIterator($files); $spawn->closures($files, function(SplFileInfo $file) { // upload this file }) ->start();
每个闭包都使用 PhpProcess 组件独立执行。
创建一个独立的单个闭包
$spawn = new Spawn(); $sum = 3; $processes = $spawn ->spawn(["super", 120], function($prefix, $number) use ($sum) { echo $prefix." heavy routine"; return $number+$sum; }); // do something else here echo $processes->wait(); // 123 echo $processes->getOutput(); // "super heavy routine"
高级
- 可调用在新的独立进程中执行,同时也使用其 "use" 引用。
- 可以添加事件处理监听器。
- 可以获取每个可调用的返回值、错误输出、输出以及其他信息。
$collaborator = new YourCollaborator(1,2,3,4); $spawn ->closures(range(1, 7), function($input) use ($collaborator) { echo "this is the echo"; $collaborator->doSomething(); $return = new \stdClass(); $return->name = "name"; return $return; }) ->onCompleted(function(ClosureProcess $process){ // do something with $returnValue = $processes->getReturnValue(); $output = $processes->getOutput(); $errorOutput = $processes->getErrorOutput(); $time = $processes->startAt(); $memory = $processes->getMemory(); $duration = $processes->getDuration(); }) ->start();
事件
监听器可以附加到 闭包
和 进程
。
->onStarted(function(ClosureProcess|Process $process){}); ->onCompleted(function(ClosureProcess|Process $process){}); ->onSuccessful(function(ClosureProcess|Process $process){}); ->onEmptyIterator(function (){}); ->onPartialOutput(function(ClosureProcess|Process $process){}) ->onLoopCompleted(function ($exitCode, StopwatchEvent $event)
其他库
处理并发进程的库并不多。我发现最好的是用于进程分叉的库 spork,它具有出色的 API,无需任何解决方案,但需要几个 PHP 扩展。
许可证
MIT 许可证,请参阅 许可证。
更多乐趣?
- 查看如何使用 travis.yml 运行测试套件 spawn_tests。
- 享受 fastest 的乐趣