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

288 lines
7.8 KiB
PHP
Raw Normal View History

2015-07-14 00:30:59 +02:00
<?php
namespace Icicle\Concurrent\Threading;
2015-08-27 16:10:08 +02:00
use Icicle\Concurrent\ContextInterface;
use Icicle\Concurrent\Exception\InvalidArgumentError;
use Icicle\Concurrent\Exception\StatusError;
use Icicle\Concurrent\Exception\SynchronizationError;
2015-08-28 23:18:02 +02:00
use Icicle\Concurrent\Exception\ThreadException;
use Icicle\Concurrent\Exception\UnsupportedError;
use Icicle\Concurrent\Sync\Channel;
use Icicle\Concurrent\Sync\ChannelInterface;
use Icicle\Concurrent\Sync\Internal\ExitStatusInterface;
use Icicle\Coroutine;
2015-10-17 01:20:20 +02:00
use Icicle\Stream;
use Icicle\Stream\Pipe\DuplexPipe;
2015-07-27 00:53:00 +02:00
/**
* Implements an execution context using native multi-threading.
2015-08-11 00:38:58 +02:00
*
* The thread context is not itself threaded. A local instance of the context is
* maintained both in the context that creates the thread and in the thread
* itself.
*/
class Thread implements ChannelInterface, ContextInterface
2015-07-14 00:30:59 +02:00
{
2015-08-25 16:39:58 +02:00
const LATENCY_TIMEOUT = 0.01; // 10 ms
2015-07-27 00:53:00 +02:00
/**
2015-08-31 00:52:00 +02:00
* @var Internal\Thread An internal thread instance.
2015-07-27 00:53:00 +02:00
*/
private $thread;
2015-07-27 00:53:00 +02:00
/**
* @var \Icicle\Concurrent\Sync\Channel A channel for communicating with the thread.
*/
private $channel;
/**
* @var \Icicle\Stream\Pipe\DuplexPipe
*/
private $pipe;
/**
* @var resource
*/
private $socket;
/**
* @var callable
*/
private $function;
/**
* @var mixed[]
*/
private $args;
2015-09-08 19:55:29 +02:00
/**
2015-09-19 05:20:35 +02:00
* @var int
2015-09-08 19:55:29 +02:00
*/
2015-09-19 05:20:35 +02:00
private $oid = 0;
2015-09-08 19:55:29 +02:00
/**
* Checks if threading is enabled.
*
* @return bool True if threading is enabled, otherwise false.
*/
public static function enabled()
{
return extension_loaded('pthreads');
}
2015-08-07 01:59:25 +02:00
/**
* Spawns a new thread and runs it.
*
2015-08-31 00:52:00 +02:00
* @param callable $function The callable to invoke in the thread.
*
2015-08-31 00:52:00 +02:00
* @return Thread The thread object that was spawned.
2015-08-07 01:59:25 +02:00
*/
public static function spawn(callable $function /* , ...$args */)
{
2015-08-24 17:47:36 +02:00
$class = new \ReflectionClass(__CLASS__);
$thread = $class->newInstanceArgs(func_get_args());
$thread->start();
return $thread;
}
2015-08-18 17:12:06 +02:00
/**
2015-08-31 00:52:00 +02:00
* Creates a new thread.
*
2015-08-31 00:52:00 +02:00
* @param callable $function The callable to invoke in the thread when run.
*
* @throws InvalidArgumentError If the given function cannot be safely invoked in a thread.
2015-08-18 17:12:06 +02:00
*/
public function __construct(callable $function /* , ...$args */)
{
if (!self::enabled()) {
throw new UnsupportedError("The pthreads extension is required to create threads.");
}
$args = array_slice(func_get_args(), 1);
// Make sure closures don't `use` other variables or have statics.
if ($function instanceof \Closure) {
$reflector = new \ReflectionFunction($function);
if (!empty($reflector->getStaticVariables())) {
throw new InvalidArgumentError('Closures with static variables cannot be passed to thread.');
}
}
$this->function = $function;
$this->args = $args;
}
/**
* Returns the thread to the condition before starting. The new thread can be started and run independently of the
* first thread.
*/
public function __clone()
{
$this->thread = null;
$this->socket = null;
$this->pipe = null;
$this->channel = null;
2015-09-19 05:20:35 +02:00
$this->oid = 0;
}
/**
* Kills the thread if it is still running.
*
* @throws \Icicle\Concurrent\Exception\ThreadException
*/
public function __destruct()
{
if (getmypid() === $this->oid) {
$this->kill();
}
}
2015-08-18 17:12:06 +02:00
2015-07-27 00:53:00 +02:00
/**
* Checks if the context is running.
2015-07-27 00:53:00 +02:00
*
* @return bool True if the context is running, otherwise false.
2015-07-27 00:53:00 +02:00
*/
public function isRunning()
{
return null !== $this->thread && $this->thread->isRunning() && null !== $this->pipe && $this->pipe->isOpen();
2015-08-07 01:59:25 +02:00
}
/**
2015-08-31 00:52:00 +02:00
* Spawns the thread and begins the thread's execution.
*
* @throws \Icicle\Concurrent\Exception\StatusError If the thread has already been started.
* @throws \Icicle\Concurrent\Exception\ThreadException If starting the thread was unsuccessful.
2015-10-17 01:20:20 +02:00
* @throws \Icicle\Stream\Exception\FailureException If creating a socket pair fails.
*/
public function start()
2015-07-14 00:30:59 +02:00
{
2015-09-19 05:20:35 +02:00
if (0 !== $this->oid) {
throw new StatusError('The thread has already been started.');
}
2015-09-19 05:20:35 +02:00
$this->oid = getmypid();
2015-09-08 19:55:29 +02:00
2015-10-17 01:20:20 +02:00
list($channel, $this->socket) = Stream\pair();
$this->thread = new Internal\Thread($this->socket, $this->function, $this->args);
if (!$this->thread->start(PTHREADS_INHERIT_INI | PTHREADS_INHERIT_FUNCTIONS | PTHREADS_INHERIT_CLASSES)) {
throw new ThreadException('Failed to start the thread.');
}
$this->channel = new Channel($this->pipe = new DuplexPipe($channel));
}
2015-08-11 00:38:58 +02:00
/**
* Immediately kills the context.
2015-08-31 00:52:00 +02:00
*
* @throws ThreadException If killing the thread was unsuccessful.
*/
public function kill()
{
2015-09-06 21:59:24 +02:00
if (null !== $this->thread) {
2015-09-08 19:55:29 +02:00
try {
if ($this->thread->isRunning() && !$this->thread->kill()) {
throw new ThreadException('Could not kill thread.');
}
} finally {
$this->close();
2015-09-06 21:59:24 +02:00
}
}
}
/**
* Closes channel and socket if still open.
*/
private function close()
{
if (null !== $this->pipe && $this->pipe->isOpen()) {
$this->pipe->close();
}
if (is_resource($this->socket)) {
fclose($this->socket);
2015-08-28 23:18:02 +02:00
}
2015-09-08 19:55:29 +02:00
$this->thread = null;
$this->channel = null;
}
2015-08-18 17:12:06 +02:00
/**
* @coroutine
*
* Gets a promise that resolves when the context ends and joins with the
* parent context.
2015-08-18 17:12:06 +02:00
*
* @return \Generator
*
* @resolve mixed Resolved with the return or resolution value of the context once it has completed execution.
*
* @throws StatusError Thrown if the context has not been started.
2015-08-31 00:52:00 +02:00
* @throws SynchronizationError Thrown if an exit status object is not received.
2015-08-18 17:12:06 +02:00
*/
public function join()
2015-08-18 17:12:06 +02:00
{
2015-09-08 19:55:29 +02:00
if (null === $this->channel || null === $this->thread) {
throw new StatusError('The thread has not been started or has already finished.');
}
2015-08-18 17:12:06 +02:00
try {
$response = (yield $this->channel->receive());
if (!$response instanceof ExitStatusInterface) {
throw new SynchronizationError('Did not receive an exit status from thread.');
2015-08-18 17:12:06 +02:00
}
yield $response->getResult();
$this->thread->join();
} catch (\Exception $exception) {
$this->kill();
throw $exception;
2015-08-18 17:12:06 +02:00
}
$this->close();
2015-08-18 17:12:06 +02:00
}
/**
* {@inheritdoc}
2015-08-18 17:12:06 +02:00
*/
public function receive()
2015-08-18 17:12:06 +02:00
{
2015-09-08 19:55:29 +02:00
if (null === $this->channel) {
throw new StatusError('The thread has not been started or has already finished.');
}
$data = (yield $this->channel->receive());
if ($data instanceof ExitStatusInterface) {
2015-09-02 23:34:42 +02:00
$this->kill();
$data = $data->getResult();
throw new SynchronizationError(sprintf(
'Thread unexpectedly exited with result of type: %s',
is_object($data) ? get_class($data) : gettype($data)
));
}
yield $data;
2015-08-18 17:12:06 +02:00
}
2015-08-07 01:59:25 +02:00
/**
* {@inheritdoc}
2015-08-07 01:59:25 +02:00
*/
public function send($data)
{
2015-09-08 19:55:29 +02:00
if (null === $this->channel) {
throw new StatusError('The thread has not been started or has already finished.');
}
if ($data instanceof ExitStatusInterface) {
2015-09-02 23:34:42 +02:00
$this->kill();
throw new InvalidArgumentError('Cannot send exit status objects.');
2015-07-27 00:53:00 +02:00
}
2015-07-14 00:30:59 +02:00
yield $this->channel->send($data);
}
2015-07-14 00:30:59 +02:00
}