2015-08-27 16:10:08 +02:00
|
|
|
<?php
|
|
|
|
namespace Icicle\Concurrent\Worker;
|
|
|
|
|
|
|
|
use Icicle\Concurrent\ContextInterface;
|
|
|
|
use Icicle\Concurrent\Exception\SynchronizationError;
|
|
|
|
use Icicle\Concurrent\Worker\Internal\TaskFailure;
|
|
|
|
|
|
|
|
class Worker implements WorkerInterface
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @var \Icicle\Concurrent\ContextInterface
|
|
|
|
*/
|
|
|
|
private $context;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var bool
|
|
|
|
*/
|
|
|
|
private $idle = true;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @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}
|
|
|
|
*/
|
2015-09-01 23:20:57 +02:00
|
|
|
public function enqueue(TaskInterface $task)
|
2015-08-27 16:10:08 +02:00
|
|
|
{
|
|
|
|
if (!$this->context->isRunning()) {
|
2015-08-29 03:30:53 +02:00
|
|
|
throw new SynchronizationError('The worker has not been started.');
|
2015-08-27 16:10:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
$this->idle = false;
|
|
|
|
|
2015-09-01 23:20:57 +02:00
|
|
|
yield $this->context->send($task);
|
2015-08-27 20:06:39 +02:00
|
|
|
|
2015-08-27 16:10:08 +02:00
|
|
|
$result = (yield $this->context->receive());
|
|
|
|
|
|
|
|
$this->idle = true;
|
|
|
|
|
|
|
|
if ($result instanceof TaskFailure) {
|
2015-08-27 20:06:39 +02:00
|
|
|
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-02 15:51:59 +02:00
|
|
|
if (!$this->context->isRunning()) {
|
|
|
|
throw new SynchronizationError('The worker is not running.');
|
|
|
|
}
|
|
|
|
|
2015-09-01 23:20:57 +02:00
|
|
|
yield $this->context->send(0);
|
2015-08-29 03:30:53 +02:00
|
|
|
|
|
|
|
yield $this->context->join();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
|
|
|
public function kill()
|
|
|
|
{
|
|
|
|
$this->context->kill();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2015-09-04 06:35:58 +02:00
|
|
|
* Kills the worker when it is destroyed.
|
2015-08-29 03:30:53 +02:00
|
|
|
*/
|
|
|
|
public function __destruct()
|
|
|
|
{
|
2015-09-04 06:35:58 +02:00
|
|
|
if ($this->context->isRunning()) {
|
|
|
|
$this->context->kill();
|
2015-08-29 03:30:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|