1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-02 17:52:14 +01:00
parallel/lib/Worker/TaskRunner.php

60 lines
1.4 KiB
PHP
Raw Normal View History

2016-12-30 02:16:04 +01:00
<?php
2015-08-27 16:10:08 +02:00
namespace Amp\Parallel\Worker;
2015-08-27 16:10:08 +02:00
2017-05-18 09:51:31 +02:00
use Amp\Coroutine;
use Amp\Parallel\Sync\Channel;
use Amp\Promise;
use function Amp\call;
2016-08-18 18:04:48 +02:00
class TaskRunner {
2016-08-26 17:10:03 +02:00
/** @var \Amp\Parallel\Sync\Channel */
2015-08-27 16:10:08 +02:00
private $channel;
2016-08-26 17:10:03 +02:00
/** @var \Amp\Parallel\Worker\Environment */
2015-09-10 06:29:41 +02:00
private $environment;
2016-08-18 18:04:48 +02:00
public function __construct(Channel $channel, Environment $environment) {
2015-08-27 16:10:08 +02:00
$this->channel = $channel;
2015-09-10 06:29:41 +02:00
$this->environment = $environment;
2015-08-27 16:10:08 +02:00
}
2017-05-18 09:51:31 +02:00
2016-08-18 18:04:48 +02:00
/**
* Runs the task runner, receiving tasks from the parent and sending the result of those tasks.
*
* @return \Amp\Promise
2016-08-18 18:04:48 +02:00
*/
2016-11-15 00:43:44 +01:00
public function run(): Promise {
2016-08-18 18:04:48 +02:00
return new Coroutine($this->execute());
}
2017-05-18 09:51:31 +02:00
2015-08-27 16:10:08 +02:00
/**
* @coroutine
*
* @return \Generator
*/
2016-08-18 18:04:48 +02:00
private function execute(): \Generator {
$job = yield $this->channel->receive();
2015-08-27 16:10:08 +02:00
while ($job instanceof Internal\Job) {
$task = $job->getTask();
2017-05-18 09:51:31 +02:00
$result = call([$task, 'run'], $this->environment);
2017-05-18 09:51:31 +02:00
2017-03-22 00:45:23 +01:00
$result->onResolve(function ($exception, $value) use ($job) {
if ($exception) {
$result = new Internal\TaskFailure($job->getId(), $exception);
} else {
$result = new Internal\TaskSuccess($job->getId(), $value);
}
2017-05-18 09:51:31 +02:00
$this->channel->send($result);
});
2015-08-27 16:10:08 +02:00
$job = yield $this->channel->receive();
2015-08-27 16:10:08 +02:00
}
return $job;
2015-08-27 16:10:08 +02:00
}
}