1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-02 09:37:57 +01:00
parallel/examples/worker-pool.php

47 lines
1.3 KiB
PHP
Raw Normal View History

#!/usr/bin/env php
<?php
require dirname(__DIR__).'/vendor/autoload.php';
2016-08-18 18:04:48 +02:00
use Amp\Concurrent\Worker\DefaultPool;
use Amp\Coroutine;
use Amp\Examples\Concurrent\BlockingTask;
2016-08-18 18:04:48 +02:00
Amp\execute(function() {
$timer = Amp\repeat(100, function () {
printf(".\n");
});
Amp\unreference($timer);
2015-12-05 06:50:32 +01:00
$pool = new DefaultPool();
2015-09-28 05:46:57 +02:00
$pool->start();
2016-01-15 01:16:07 +01:00
$coroutines = [];
2016-08-18 18:04:48 +02:00
$coroutines[] = function () use ($pool) {
2016-01-15 01:16:07 +01:00
$url = 'https://google.com';
2016-08-18 18:04:48 +02:00
$result = yield $pool->enqueue(new BlockingTask('file_get_contents', $url));
2016-01-15 01:16:07 +01:00
printf("Read from %s: %d bytes\n", $url, strlen($result));
2016-08-18 18:04:48 +02:00
};
2016-01-15 01:16:07 +01:00
2016-08-18 18:04:48 +02:00
$coroutines[] = function () use ($pool) {
$url = 'http://amphp.org';
$result = yield $pool->enqueue(new BlockingTask('file_get_contents', $url));
2016-01-15 01:16:07 +01:00
printf("Read from %s: %d bytes\n", $url, strlen($result));
2016-08-18 18:04:48 +02:00
};
2016-08-18 18:04:48 +02:00
$coroutines[] = function () use ($pool) {
2016-01-15 01:16:07 +01:00
$url = 'https://github.com';
2016-08-18 18:04:48 +02:00
$result = yield $pool->enqueue(new BlockingTask('file_get_contents', $url));
2016-01-15 01:16:07 +01:00
printf("Read from %s: %d bytes\n", $url, strlen($result));
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
2016-08-18 18:04:48 +02:00
yield Amp\all($coroutines);
2016-08-18 18:04:48 +02:00
return yield $pool->shutdown();
});
2015-09-28 05:46:57 +02:00