superrb / async
一个用于通过套接字处理异步进程和进程间通信的PHP库
This package is auto-updated.
Last update: 2024-08-26 14:59:45 UTC
README
一个简单的PHP库,用于创建异步进程,并通过套接字处理进程间通信。
安装
composer require superrb/async
用法
入门
使用此包最简单的方法是使用async
助手。这将在一个分支进程中异步运行提供的闭包。闭包必须返回一个布尔值以指示子进程的成功/失败,并且返回类型必须是bool
,因为这将用于设置进程的退出状态。
echo 1."\n"; async(function(): bool { sleep(1); echo 2."\n"; return true; }); echo 3."\n"; // Output 1 3 2
传递给async
的任何参数将直接传递到分支进程中。
async(function($i, $j): bool { echo $i."\n"; echo $j."\n"; return true; }, 1, 2); // Output 1 2
可重用闭包
您可以通过手动构造Superrb\Async\Handler
的实例来重用闭包
$handler = new Superrb\Async\Handler(function(int $i): bool { echo $i; return true; }); for ($i = 0; $i < 10; $i++) { $handler->run($i); } // Processing will pause here until all asynchronous processes // have completed. $success is true if all processes returned // true, otherwise it is false $success = $handler->waitAll();
您可以通过将Handler
构造函数的第二个参数设置为false
,在分支进程中运行同步代码。这对于运行长时间进程(如导入)很有用,因为循环中消耗的任何内存都将在进程结束时被清空。
$handler = new Superrb\Async\Handler(function(int $i): bool { echo $i; return true; }, false); for ($i = 0; $i < 10; $i++) { // The loop will pause whilst the process runs, and continue // when it is completed. $success is the return value of the // closure $success = $handler->run($i); }
进程间通信
向父进程发送消息
async
使用通道和套接字对允许子进程和父进程之间的通信。通信是单向的 - 您可以通过在闭包中使用$this->send()
将消息从子进程传递回主进程。消息可以是字符串、对象或数组。
$handler = new Superrb\Async\Handler(function(int $i): bool { $this->send('Hi from process '.$i); return true; }); for ($i = 0; $i < 10; $i++) { $handler->run($i); } $handler->waitAll();
读取消息
处理完成后,可以通过调用生成器$handler->getMessages()
来读取消息。对于异步进程,消息总是按照处理器的运行顺序接收,而不管哪个进程先完成。
foreach($handler->getMessages() as $message) { echo $message."\n"; } // output Hi from process 1 Hi from process 2 Hi from process 3 ...
对于同步进程,您可以在每个进程结束时读取消息。如果您这样做,您需要手动在读取后清空消息池。
for ($i = 0; $i < 10; $i++) { $handler->run($i); foreach($handler->getMessages() as $message) { echo $message."\n"; } $handler->clearMessages(); }
增加通信缓冲区
默认情况下,消息在1024字节的缓冲区中发送,尝试发送大于此大小的数据将导致异常。您可以通过在处理器上调用setMessageBuffer
来增加/减少缓冲区。
$handler->setMessageBuffer(4096);
贡献
我们欢迎并鼓励所有贡献。请阅读我们的贡献指南和行为准则以获取更多信息。
许可证
版权(c)2017 Superrb Studio tech@superrb.com
Async采用MIT许可证(MIT)授权
团队
- James Dinsdale (@molovo)