1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-02 17:52:14 +01:00
parallel/lib/Threading/Thread.php

312 lines
8.8 KiB
PHP
Raw Normal View History

2016-12-30 02:16:04 +01:00
<?php
2015-07-14 00:30:59 +02:00
2016-08-23 23:47:40 +02:00
namespace Amp\Parallel\Threading;
2016-08-18 18:04:48 +02:00
2017-05-18 09:51:31 +02:00
use Amp\Coroutine;
use Amp\Loop;
use Amp\Parallel\ContextException;
use Amp\Parallel\StatusError;
use Amp\Parallel\Strand;
use Amp\Parallel\Sync\ChannelException;
use Amp\Parallel\Sync\ChannelledSocket;
use Amp\Parallel\Sync\ExitResult;
2017-05-18 09:51:31 +02:00
use Amp\Parallel\SynchronizationError;
use Amp\Promise;
use function Amp\call;
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.
*/
2016-08-18 18:04:48 +02:00
class Thread implements Strand {
2017-03-09 23:55:11 +01:00
const EXIT_CHECK_FREQUENCY = 250;
2016-08-26 17:10:03 +02:00
/** @var Internal\Thread An internal thread instance. */
private $thread;
2015-07-27 00:53:00 +02:00
2016-08-31 01:27:14 +02:00
/** @var \Amp\Parallel\Sync\ChannelledSocket A channel for communicating with the thread. */
private $channel;
2016-08-26 17:10:03 +02:00
/** @var resource */
private $socket;
2016-08-26 17:10:03 +02:00
/** @var callable */
private $function;
2016-08-26 17:10:03 +02:00
/** @var mixed[] */
private $args;
2016-08-26 17:10:03 +02:00
/** @var int */
2015-09-19 05:20:35 +02:00
private $oid = 0;
2015-09-08 19:55:29 +02:00
2017-03-09 23:55:11 +01:00
/** @var string */
private $watcher;
/**
* Checks if threading is enabled.
*
* @return bool True if threading is enabled, otherwise false.
*/
2016-08-18 18:04:48 +02:00
public static function supported(): bool {
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
*/
2016-08-18 18:04:48 +02:00
public static function spawn(callable $function, ...$args) {
2016-01-23 07:00:56 +01:00
$thread = new self($function, ...$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.
*
2016-08-18 18:04:48 +02:00
* @throws \Error Thrown if the pthreads extension is not available.
2015-08-18 17:12:06 +02:00
*/
2016-08-18 18:04:48 +02:00
public function __construct(callable $function, ...$args) {
if (!self::supported()) {
throw new \Error("The pthreads extension is required to create threads.");
}
$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.
*/
2016-08-18 18:04:48 +02:00
public function __clone() {
$this->thread = null;
$this->socket = null;
$this->channel = null;
2015-09-19 05:20:35 +02:00
$this->oid = 0;
}
/**
* Kills the thread if it is still running.
*
2016-08-23 23:47:40 +02:00
* @throws \Amp\Parallel\ContextException
2015-09-19 05:20:35 +02:00
*/
2016-08-18 18:04:48 +02:00
public function __destruct() {
if (\getmypid() === $this->oid) {
2015-09-19 05:20:35 +02:00
$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
*/
2016-08-18 18:04:48 +02:00
public function isRunning(): bool {
2016-08-31 01:27:14 +02:00
return $this->channel !== null;
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.
*
2016-08-23 23:47:40 +02:00
* @throws \Amp\Parallel\StatusError If the thread has already been started.
* @throws \Amp\Parallel\ContextException If starting the thread was unsuccessful.
*/
2016-08-18 18:04:48 +02:00
public function start() {
2016-08-23 01:25:19 +02:00
if ($this->oid !== 0) {
throw new StatusError('The thread has already been started.');
}
2016-08-18 18:04:48 +02:00
$this->oid = \getmypid();
2015-09-08 19:55:29 +02:00
2016-08-31 01:27:14 +02:00
$sockets = @\stream_socket_pair(
2016-09-02 01:10:52 +02:00
\stripos(\PHP_OS, "win") === 0 ? STREAM_PF_INET : STREAM_PF_UNIX,
2016-08-31 01:27:14 +02:00
STREAM_SOCK_STREAM,
STREAM_IPPROTO_IP
);
if ($sockets === false) {
$message = "Failed to create socket pair";
if ($error = \error_get_last()) {
$message .= \sprintf(" Errno: %d; %s", $error["type"], $error["message"]);
}
throw new ContextException($message);
}
list($channel, $this->socket) = $sockets;
$this->thread = new Internal\Thread($this->socket, $this->function, $this->args);
2016-08-18 18:04:48 +02:00
if (!$this->thread->start(PTHREADS_INHERIT_INI)) {
throw new ContextException('Failed to start the thread.');
}
$this->channel = new ChannelledSocket($channel, $channel);
2017-03-09 23:55:11 +01:00
2017-06-01 18:15:03 +02:00
$this->watcher = Loop::repeat(self::EXIT_CHECK_FREQUENCY, function ($watcher) {
if (!$this->thread->isRunning()) {
2017-06-01 18:15:03 +02:00
// Delay call to close to avoid race condition between thread exiting and data becoming available.
Loop::delay(self::EXIT_CHECK_FREQUENCY, function () {
$this->close();
});
Loop::disable($watcher);
2017-03-09 23:55:11 +01:00
}
});
Loop::disable($this->watcher);
}
2015-08-11 00:38:58 +02:00
/**
* Immediately kills the context.
2015-08-31 00:52:00 +02:00
*
2016-08-18 18:04:48 +02:00
* @throws ContextException If killing the thread was unsuccessful.
*/
2016-08-18 18:04:48 +02:00
public function kill() {
2016-08-23 01:25:19 +02:00
if ($this->thread !== null) {
2015-09-08 19:55:29 +02:00
try {
if ($this->thread->isRunning() && !$this->thread->kill()) {
2016-08-18 18:04:48 +02:00
throw new ContextException('Could not kill thread.');
2015-09-08 19:55:29 +02:00
}
} finally {
$this->close();
2015-09-06 21:59:24 +02:00
}
}
}
/**
* Closes channel and socket if still open.
*/
2016-08-18 18:04:48 +02:00
private function close() {
2016-08-31 01:27:14 +02:00
if ($this->channel !== null) {
$this->channel->close();
}
2016-08-18 18:04:48 +02:00
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;
2017-03-09 23:55:11 +01:00
Loop::cancel($this->watcher);
}
2015-08-18 17:12:06 +02:00
/**
* Gets a promise that resolves when the context ends and joins with the
* parent context.
2015-08-18 17:12:06 +02:00
*
* @return \Amp\Promise<mixed>
*
* @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.
* @throws ContextException If the context stops responding.
2015-08-18 17:12:06 +02:00
*/
2016-11-15 00:43:44 +01:00
public function join(): Promise {
2016-08-23 01:25:19 +02:00
if ($this->channel == null || $this->thread === null) {
2015-09-08 19:55:29 +02:00
throw new StatusError('The thread has not been started or has already finished.');
}
2016-08-18 18:04:48 +02:00
return new Coroutine($this->doJoin());
}
2016-08-18 18:04:48 +02:00
/**
* @coroutine
*
* @return \Generator
*
* @throws SynchronizationError If the thread does not send an exit status.
* @throws ContextException If the context stops responding.
2016-08-18 18:04:48 +02:00
*/
private function doJoin(): \Generator {
Loop::enable($this->watcher);
2015-08-18 17:12:06 +02:00
try {
2016-08-18 18:04:48 +02:00
$response = yield $this->channel->receive();
2017-01-17 06:24:59 +01:00
if (!$response instanceof ExitResult) {
throw new SynchronizationError('Did not receive an exit result from thread.');
2015-08-18 17:12:06 +02:00
}
} catch (ChannelException $exception) {
$this->kill();
throw new ContextException(
2017-07-21 06:58:13 +02:00
"The context stopped responding, potentially due to a fatal error or calling exit",
0,
$exception
);
2016-01-23 07:00:56 +01:00
} catch (\Throwable $exception) {
$this->kill();
throw $exception;
2016-09-07 18:38:46 +02:00
} finally {
Loop::disable($this->watcher);
2016-09-07 18:38:46 +02:00
$this->close();
2015-08-18 17:12:06 +02:00
}
2016-09-07 18:38:46 +02:00
return $response->getResult();
2015-08-18 17:12:06 +02:00
}
/**
* {@inheritdoc}
2015-08-18 17:12:06 +02:00
*/
2016-11-15 00:43:44 +01:00
public function receive(): Promise {
2016-08-23 01:25:19 +02:00
if ($this->channel === null) {
2016-08-18 18:04:48 +02:00
throw new StatusError('The process has not been started.');
}
return new Coroutine($this->doReceive());
}
private function doReceive() {
Loop::enable($this->watcher);
try {
$data = yield $this->channel->receive();
2017-07-21 06:58:13 +02:00
} catch (ChannelException $e) {
throw new ContextException("The context stopped responding, potentially due to a fatal error or calling exit", 0, $e);
} finally {
Loop::disable($this->watcher);
}
2017-03-09 23:48:34 +01:00
if ($data instanceof ExitResult) {
$data = $data->getResult();
throw new SynchronizationError(\sprintf(
'Thread process unexpectedly exited with result of type: %s',
\is_object($data) ? \get_class($data) : \gettype($data)
));
}
return $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
*/
2016-11-15 00:43:44 +01:00
public function send($data): Promise {
2016-08-23 01:25:19 +02:00
if ($this->channel === null) {
2015-09-08 19:55:29 +02:00
throw new StatusError('The thread has not been started or has already finished.');
}
2017-01-17 06:24:59 +01:00
if ($data instanceof ExitResult) {
throw new \Error('Cannot send exit result objects.');
2015-07-27 00:53:00 +02:00
}
2015-07-14 00:30:59 +02:00
return call(function () use ($data) {
2017-05-28 07:09:13 +02:00
Loop::enable($this->watcher);
try {
yield $this->channel->send($data);
} catch (ChannelException $e) {
2017-07-21 06:58:13 +02:00
throw new ContextException("The context went away, potentially due to a fatal error or calling exit", 0, $e);
2017-05-28 07:09:13 +02:00
} finally {
Loop::disable($this->watcher);
}
});
}
2015-07-14 00:30:59 +02:00
}