cheprasov/php-parallel

该类允许你在不同的进程中并行运行多个操作并将结果发送到主进程。当你需要同时运行多个独立的操作,而不是按顺序执行时,或者当你运行多个独立的查询,例如查询不同的数据库时,非常有用。

1.2.0 2016-07-27 21:26 UTC

This package is not auto-updated.

Last update: 2024-09-23 11:53:27 UTC


README

该类允许你在不同的线程中并行运行多个操作并将结果发送到主进程。当你需要同时运行多个独立的操作,而不是按顺序执行时,或者当你运行多个独立的查询,例如查询不同的数据库时,非常有用。

通信

进程间的数据通信是通过一个(或多个)存储实现的

  • APCu
  • Memcached
  • Redis

使用

<?php

require (dirname(__DIR__).'/vendor/autoload.php');

use Parallel\Parallel;
use Parallel\Storage\ApcuStorage;

// EXAMPLE, how to run parallel 3 operations.

// Using Parallel via ApcuStorage (APCu, see https://php.ac.cn/manual/ru/book.apcu.php)
$Parallel = new Parallel(new ApcuStorage());

// if you have not APCu, you can use Memcached or Redis as Storage.
// Note: you can't store objects in Memcached or Redis and you can't store binary strings (use <base64> functions)

//    $Parallel = new Parallel(new \Parallel\Storage\MemcachedStorage([
//        'servers' => [['127.0.0.1', 11211]]
//    ]));

//    $Parallel = new Parallel(new \Parallel\Storage\RedisStorage([
//        'server' => 'tcp://127.0.0.1:6379'
//    ]));

$time = microtime(true);

// 1st operation
$Parallel->run('foo', function() {
    // You can use Parallel inside run function by creating new objects Parallel.
    // Example: $Parallel = new Parallel(new \Parallel\Storage\ApcuStorage());
    sleep(2);
    return ['hello' => 'world'];
});

// 2nd operation
$Parallel->run('obj', function() {
    sleep(2);
    return (object) ['a' => 1, 'b' => 2, 'c' => 3];
});

// 3th operation
// do some thing ...
sleep(2);

// waiting for <foo> and <obj> and get results.
// use wait() without parameters for wait all forks. Example: $Parallel->wait();
$result = $Parallel->wait(['foo', 'obj']);

print_r($result);
print_r(microtime(true) - $time);
// 3 parallel operations by 2 seconds take about 2 seconds, instead 6 seconds.

//    Array
//    (
//        [foo] => Array
//            (
//                [hello] => world
//            )
//
//        [obj] => stdClass Object
//            (
//                [a] => 1
//                [b] => 2
//                [c] => 3
//            )
//    )
//    2.0130307674408

安装

Composer

下载 composer

wget -nc https://getcomposer.org.cn/composer.phar

并将依赖添加到你的项目中

php composer.phar require cheprasov/php-parallel

运行测试

在控制台中输入以下命令以运行测试

./vendor/bin/phpunit

有些东西不工作

请随意分支项目,修复错误,并最终请求合并