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

108 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;
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}
*/
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;
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()
{
if (!$this->context->isRunning()) {
throw new SynchronizationError('The worker is not running.');
}
yield $this->context->send(0);
2015-08-29 03:30:53 +02:00
yield $this->context->join();
}
/**
* {@inheritdoc}
*/
public function kill()
{
$this->context->kill();
}
/**
* Kills the worker when it is destroyed.
2015-08-29 03:30:53 +02:00
*/
public function __destruct()
{
if ($this->context->isRunning()) {
$this->context->kill();
2015-08-29 03:30:53 +02:00
}
}
}