lifo / php-ipc
简单的 PHP 进程间通信(IPC)库
v1.1
2016-01-26 18:37 UTC
Requires
- php: >=5.3.0
- ext-pcntl: *
This package is auto-updated.
Last update: 2024-09-14 02:40:18 UTC
README
进程间通信
这个库还处于初级阶段。我会根据我在其他项目中需要的功能来添加功能。
示例
ProcessPool
ProcessPool 类提供了一个非常简单的接口来管理一个子进程列表,这些子进程返回 1 个或多个结果并退出。每个子进程可以返回任何可以被 序列化 的值。
<?php use Lifo\IPC\ProcessPool; // create a pool with a maximum of 16 workers at a time $pool = new ProcessPool(16); // apply 100 processes to the pool. for ($i=0; $i<100; $i++) { $pool->apply(function($parent) use ($i) { // Each child can write to the $parent socket to send more than a single // result. Make sure you use ProcessPool::socket_send() ProcessPool::socket_send($parent, "$i says the time is " . time()); // Results can be any serializable value ProcessPool::socket_send($parent, array('date' => date('Y-m-d'), 'time' => time())); // Each child can optionally return a result or just use socket_send // as shown above. mt_srand(); // must re-seed for each child $rand = mt_rand(1000000, 2000000); usleep($rand); return $i . ' : slept for ' . ($rand / 1000000) . ' seconds'; }); } // wait for all results to be finished ... while ($pool->getPending()) { try { $result = $pool->get(1); // timeout in 1 second echo "GOT: ", $result, "\n"; } catch (\Exception $e) { // timeout } } // easy shortcut to get all results at once. $results = $pool->getAll();
高级 ProcessPool 示例
<?php use Lifo\IPC\ProcessPool; // Pretend we have open resources like a DB connection... $db = mysqli_connect(...); // create a pool $pool = new ProcessPool(); // set a callback that is called everytime a child is forked $pool->setOnCreate(function() use (&$db) { // reconnect to the DB $db = mysqli_connect(...); }); // create a child $pool->apply(function($parent) use (&$db) { // do stuff in the child; When we exit the $db handle will // close but won't affect the parent since it reconnected // after we were created (our $db handle is not equal to the parent $db) // ... }); $results = $pool->getAll();