2015-08-28 05:51:50 +02:00
|
|
|
#!/usr/bin/env php
|
|
|
|
<?php
|
2018-11-01 09:36:21 +01:00
|
|
|
|
|
|
|
require \dirname(__DIR__) . '/vendor/autoload.php';
|
2015-08-28 05:51:50 +02:00
|
|
|
|
2017-05-18 09:51:31 +02:00
|
|
|
use Amp\Loop;
|
2018-11-01 09:36:21 +01:00
|
|
|
use Amp\Parallel\Worker\CallableTask;
|
2017-05-18 09:51:31 +02:00
|
|
|
use Amp\Parallel\Worker\DefaultPool;
|
2015-08-28 05:51:50 +02:00
|
|
|
|
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 = [
|
2018-11-08 21:29:07 +01:00
|
|
|
new CallableTask('file_get_contents', ['http://php.net']),
|
|
|
|
new CallableTask('file_get_contents', ['https://amphp.org']),
|
|
|
|
new CallableTask('file_get_contents', ['https://github.com']),
|
2017-11-20 19:21:53 +01:00
|
|
|
];
|
|
|
|
|
|
|
|
// Event loop for parallel tasks
|
2018-10-25 05:31:47 +02:00
|
|
|
Loop::run(function () use (&$results, $tasks) {
|
2017-11-20 19:21:53 +01:00
|
|
|
$timer = Loop::repeat(200, function () {
|
2018-10-07 16:50:45 +02:00
|
|
|
\printf(".");
|
2016-08-18 18:04:48 +02:00
|
|
|
});
|
2016-12-30 02:17:26 +01: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 = [];
|
|
|
|
|
2018-11-08 21:29:07 +01:00
|
|
|
foreach ($tasks as $index => $task) {
|
|
|
|
$coroutines[] = Amp\call(function () use ($pool, $index, $task) {
|
2017-11-20 19:21:53 +01:00
|
|
|
$result = yield $pool->enqueue($task);
|
2018-11-08 21:29:07 +01:00
|
|
|
\printf("\nRead from task %d: %d bytes\n", $index, \strlen($result));
|
2018-10-25 05:31:47 +02:00
|
|
|
return $result;
|
|
|
|
});
|
2017-11-20 19:21:53 +01:00
|
|
|
}
|
2017-05-18 09:51:31 +02:00
|
|
|
|
2018-10-25 05:31:47 +02:00
|
|
|
$results = yield Amp\Promise\all($coroutines);
|
2015-08-28 05:51:50 +02:00
|
|
|
|
2016-08-18 18:04:48 +02:00
|
|
|
return yield $pool->shutdown();
|
2017-03-16 23:03:59 +01:00
|
|
|
});
|
2017-11-20 19:21:53 +01:00
|
|
|
|
|
|
|
echo "\nResult array keys:\n";
|
2018-10-07 16:50:45 +02:00
|
|
|
echo \var_export(\array_keys($results), true);
|