Last active
April 26, 2018 21:15
-
-
Save kelunik/0ba6193514a13f8e22e951aa710c2220 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require __DIR__ . '/vendor/autoload.php'; | |
use Amp\Loop; | |
use Amp\Artax; | |
$queue = new SplQueue; | |
$waiting = new Amp\Deferred; | |
$http = new Artax\DefaultClient; | |
$worker = Amp\coroutine(function ($workerId) use ($queue, &$waiting, $http) { | |
while (true) { | |
while ($queue->isEmpty()) { | |
yield $waiting->promise(); | |
} | |
$uri = $queue->pop(); | |
$response = yield $http->request($uri); | |
$responseBody = yield $response->getBody(); | |
print "#" . $workerId . " - " . $uri . " → " . $response->getStatus() . " " . $response->getReason() . " (queue size: " . $queue->count() . ")" . PHP_EOL; | |
if (random_int(0, 1) === 1) { | |
$isEmpty = $queue->isEmpty(); | |
$queue->push("http://example.com/" . random_int(0, 32)); | |
$queue->push("http://example.net/" . random_int(0, 32)); | |
if ($isEmpty) { | |
$deferred = $waiting; | |
$waiting = new Amp\Deferred; | |
$deferred->resolve(); | |
} | |
} | |
} | |
}); | |
$queue->push("http://example.com/"); | |
Loop::run(function () use ($worker) { | |
// Create workers and wait for them to finish | |
yield array_map($worker, range(0, 3)); | |
// Because we automatically exit the event loop, this line will never be reached. | |
// If some end condition is known, the while (true) in the workers can be replaced | |
// and then this line will be reached once finished. | |
print "Finished processing." . PHP_EOL; // <-- Never reached | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment