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

109 lines
2.0 KiB
PHP
Raw Normal View History

2015-08-27 16:10:08 +02:00
<?php
namespace Icicle\Concurrent\Worker;
use Icicle\Concurrent\ContextInterface;
2015-09-05 19:50:41 +02:00
use Icicle\Concurrent\Exception\StatusError;
2015-08-27 16:10:08 +02:00
use Icicle\Concurrent\Worker\Internal\TaskFailure;
2015-09-09 07:18:05 +02:00
abstract class Worker implements WorkerInterface
2015-08-27 16:10:08 +02:00
{
/**
* @var \Icicle\Concurrent\ContextInterface
*/
private $context;
/**
* @var bool
*/
private $idle = true;
2015-09-26 01:01:35 +02:00
/**
* @var bool
*/
private $shutdown = false;
2015-08-27 16:10:08 +02:00
/**
* @param \Icicle\Concurrent\ContextInterface $context
*/
public function __construct(ContextInterface $context)
{
$this->context = $context;
}
/**
* {@inheritdoc}
*/
public function isRunning()
{
return $this->context->isRunning();
}
/**
* {@inheritdoc}
*/
public function isIdle()
{
return $this->idle;
}
/**
* {@inheritdoc}
*/
public function start()
{
$this->context->start();
}
/**
* {@inheritdoc}
*/
public function enqueue(TaskInterface $task)
2015-08-27 16:10:08 +02:00
{
if (!$this->context->isRunning()) {
2015-09-05 19:50:41 +02:00
throw new StatusError('The worker has not been started.');
2015-08-27 16:10:08 +02:00
}
2015-09-26 01:01:35 +02:00
if ($this->shutdown) {
throw new StatusError('The worker has been shutdown.');
}
2015-08-27 16:10:08 +02:00
$this->idle = false;
yield $this->context->send($task);
2015-08-27 16:10:08 +02:00
$result = (yield $this->context->receive());
$this->idle = true;
if ($result instanceof TaskFailure) {
throw $result->getException();
2015-08-27 16:10:08 +02:00
}
yield $result;
}
2015-08-29 03:30:53 +02:00
/**
* {@inheritdoc}
*/
public function shutdown()
{
2015-09-26 01:01:35 +02:00
if (!$this->context->isRunning() || $this->shutdown) {
2015-09-05 19:50:41 +02:00
throw new StatusError('The worker is not running.');
}
2015-09-26 01:01:35 +02:00
$this->shutdown = true;
yield $this->context->send(0);
2015-08-29 03:30:53 +02:00
yield $this->context->join();
}
/**
* {@inheritdoc}
*/
public function kill()
{
$this->context->kill();
}
}