1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-03 10:07:49 +01:00
parallel/lib/Worker/Internal/TaskRunner.php

67 lines
1.3 KiB
PHP
Raw Normal View History

2015-08-27 16:10:08 +02:00
<?php
namespace Icicle\Concurrent\Worker\Internal;
2015-12-05 06:50:32 +01:00
use Icicle\Concurrent\Sync\Channel;
2015-09-10 06:29:41 +02:00
use Icicle\Concurrent\Worker\Environment;
2015-12-05 06:50:32 +01:00
use Icicle\Concurrent\Worker\Task;
2015-08-27 16:10:08 +02:00
class TaskRunner
{
/**
* @var bool
*/
private $idle = true;
/**
2015-12-05 06:50:32 +01:00
* @var \Icicle\Concurrent\Sync\Channel
2015-08-27 16:10:08 +02:00
*/
private $channel;
2015-09-10 06:29:41 +02:00
/**
* @var \Icicle\Concurrent\Worker\Environment
*/
private $environment;
2015-12-05 06:50:32 +01: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
}
/**
* @coroutine
*
* @return \Generator
*/
2016-01-23 07:00:56 +01:00
public function run(): \Generator
2015-08-27 16:10:08 +02:00
{
2016-01-23 07:00:56 +01:00
$task = yield from $this->channel->receive();
2015-08-27 16:10:08 +02:00
2015-12-05 06:50:32 +01:00
while ($task instanceof Task) {
2015-08-27 16:10:08 +02:00
$this->idle = false;
try {
2016-01-25 06:12:03 +01:00
$result = yield $task->run($this->environment);
2016-01-23 07:00:56 +01:00
} catch (\Throwable $exception) {
2015-08-27 16:10:08 +02:00
$result = new TaskFailure($exception);
}
2016-01-23 07:00:56 +01:00
yield from $this->channel->send($result);
2015-08-27 16:10:08 +02:00
$this->idle = true;
2016-01-23 07:00:56 +01:00
$task = yield from $this->channel->receive();
2015-08-27 16:10:08 +02:00
}
2016-01-23 07:00:56 +01:00
return $task;
2015-08-27 16:10:08 +02:00
}
/**
* @return bool
*/
2016-01-23 07:00:56 +01:00
public function isIdle(): bool
2015-08-27 16:10:08 +02:00
{
return $this->idle;
}
}