2016-12-29 19:16:04 -06:00
|
|
|
<?php
|
2015-08-27 09:10:08 -05:00
|
|
|
|
2017-07-26 00:41:00 -05:00
|
|
|
namespace Amp\Parallel\Worker;
|
2015-08-27 09:10:08 -05:00
|
|
|
|
2017-05-18 09:51:31 +02:00
|
|
|
use Amp\Coroutine;
|
|
|
|
use Amp\Parallel\Sync\Channel;
|
2017-03-16 17:03:59 -05:00
|
|
|
use Amp\Promise;
|
2017-05-19 17:13:42 -05:00
|
|
|
use function Amp\call;
|
2016-08-18 11:04:48 -05:00
|
|
|
|
|
|
|
class TaskRunner {
|
2016-08-26 10:10:03 -05:00
|
|
|
/** @var \Amp\Parallel\Sync\Channel */
|
2015-08-27 09:10:08 -05:00
|
|
|
private $channel;
|
|
|
|
|
2016-08-26 10:10:03 -05:00
|
|
|
/** @var \Amp\Parallel\Worker\Environment */
|
2015-09-09 23:29:41 -05:00
|
|
|
private $environment;
|
|
|
|
|
2016-08-18 11:04:48 -05:00
|
|
|
public function __construct(Channel $channel, Environment $environment) {
|
2015-08-27 09:10:08 -05:00
|
|
|
$this->channel = $channel;
|
2015-09-09 23:29:41 -05:00
|
|
|
$this->environment = $environment;
|
2015-08-27 09:10:08 -05:00
|
|
|
}
|
2017-05-18 09:51:31 +02:00
|
|
|
|
2016-08-18 11:04:48 -05:00
|
|
|
/**
|
|
|
|
* Runs the task runner, receiving tasks from the parent and sending the result of those tasks.
|
|
|
|
*
|
2017-03-16 17:03:59 -05:00
|
|
|
* @return \Amp\Promise
|
2016-08-18 11:04:48 -05:00
|
|
|
*/
|
2016-11-14 17:43:44 -06:00
|
|
|
public function run(): Promise {
|
2016-08-18 11:04:48 -05:00
|
|
|
return new Coroutine($this->execute());
|
|
|
|
}
|
2017-05-18 09:51:31 +02:00
|
|
|
|
2015-08-27 09:10:08 -05:00
|
|
|
/**
|
|
|
|
* @coroutine
|
|
|
|
*
|
|
|
|
* @return \Generator
|
|
|
|
*/
|
2016-08-18 11:04:48 -05:00
|
|
|
private function execute(): \Generator {
|
2016-08-21 10:33:39 -05:00
|
|
|
$job = yield $this->channel->receive();
|
2015-08-27 09:10:08 -05:00
|
|
|
|
2017-07-26 00:41:00 -05:00
|
|
|
while ($job instanceof Internal\Job) {
|
2017-12-06 15:59:28 -06:00
|
|
|
try {
|
|
|
|
$result = yield call([$job->getTask(), "run"], $this->environment);
|
|
|
|
$result = new Internal\TaskSuccess($job->getId(), $result);
|
|
|
|
} catch (\Throwable $exception) {
|
|
|
|
$result = new Internal\TaskFailure($job->getId(), $exception);
|
|
|
|
}
|
2017-05-18 09:51:31 +02:00
|
|
|
|
2017-12-06 15:59:28 -06:00
|
|
|
$job = null; // Free memory from last job.
|
2015-08-27 09:10:08 -05:00
|
|
|
|
2017-12-06 15:59:28 -06:00
|
|
|
yield $this->channel->send($result);
|
|
|
|
|
|
|
|
$result = null; // Free memory from last result.
|
2017-11-10 10:32:01 -06:00
|
|
|
|
2016-08-21 10:33:39 -05:00
|
|
|
$job = yield $this->channel->receive();
|
2015-08-27 09:10:08 -05:00
|
|
|
}
|
|
|
|
|
2016-08-21 10:33:39 -05:00
|
|
|
return $job;
|
2015-08-27 09:10:08 -05:00
|
|
|
}
|
|
|
|
}
|