1
0
mirror of https://github.com/danog/parallel.git synced 2024-11-27 04:44:56 +01:00
parallel/examples/worker-pool.php

51 lines
1.3 KiB
PHP
Raw Normal View History

#!/usr/bin/env php
<?php
require dirname(__DIR__).'/vendor/autoload.php';
2017-05-18 09:51:31 +02:00
use Amp\Coroutine;
use Amp\Loop;
use Amp\Parallel\Example\BlockingTask;
use Amp\Parallel\Worker\DefaultPool;
2017-11-20 19:21:53 +01:00
// A variable to store our fetched results
$results = [];
// We can first define tasks and then run them
$tasks = [
new BlockingTask('file_get_contents', 'http://php.net'),
new BlockingTask('file_get_contents', 'https://amphp.org'),
new BlockingTask('file_get_contents', 'https://github.com'),
];
// Event loop for parallel tasks
Loop::run(function () use (&$results, &$tasks) {
$timer = Loop::repeat(200, function () {
printf(".");
2016-08-18 18:04:48 +02:00
});
Loop::unreference($timer);
2017-05-18 09:51:31 +02:00
2017-02-18 18:06:03 +01:00
$pool = new DefaultPool;
2015-09-28 05:46:57 +02:00
2016-01-15 01:16:07 +01:00
$coroutines = [];
2017-11-20 19:21:53 +01:00
foreach ($tasks as $task) {
$coroutines[] = function () use ($pool, $task, &$results) {
$result = yield $pool->enqueue($task);
$url = $task->getArgs()[0];
printf("\nRead from %s: %d bytes\n", $url, strlen($result));
$results[$url] = $result;
};
}
2017-05-18 09:51:31 +02:00
2016-08-18 18:04:48 +02:00
$coroutines = array_map(function (callable $coroutine): Coroutine {
return new Coroutine($coroutine());
}, $coroutines);
2016-01-15 01:16:07 +01:00
yield Amp\Promise\all($coroutines);
2016-08-18 18:04:48 +02:00
return yield $pool->shutdown();
});
2017-11-20 19:21:53 +01:00
echo "\nResult array keys:\n";
echo var_export(array_keys($results), true);