/
Thread.php
272 lines (233 loc) · 7.14 KB
/
Thread.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
<?php
namespace Icicle\Concurrent\Threading;
use Icicle\Concurrent\Exception\{StatusError, SynchronizationError, ThreadException};
use Icicle\Concurrent\Strand;
use Icicle\Concurrent\Sync\{ChannelledStream, Internal\ExitStatus};
use Icicle\Coroutine;
use Icicle\Exception\{InvalidArgumentError, UnsupportedError};
use Icicle\Stream;
use Icicle\Stream\Pipe\DuplexPipe;
/**
* Implements an execution context using native multi-threading.
*
* 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 Strand
{
/**
* @var Internal\Thread An internal thread instance.
*/
private $thread;
/**
* @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;
/**
* @var int
*/
private $oid = 0;
/**
* Checks if threading is enabled.
*
* @return bool True if threading is enabled, otherwise false.
*/
public static function enabled(): bool
{
return extension_loaded('pthreads');
}
/**
* Spawns a new thread and runs it.
*
* @param callable $function The callable to invoke in the thread.
*
* @return Thread The thread object that was spawned.
*/
public static function spawn(callable $function, ...$args)
{
$thread = new self($function, ...$args);
$thread->start();
return $thread;
}
/**
* Creates a new thread.
*
* @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.
* @throws UnsupportedError Thrown if the pthreads extension is not available.
*/
public function __construct(callable $function, ...$args)
{
if (!self::enabled()) {
throw new UnsupportedError("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.
*/
public function __clone()
{
$this->thread = null;
$this->socket = null;
$this->pipe = null;
$this->channel = null;
$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();
}
}
/**
* Checks if the context is running.
*
* @return bool True if the context is running, otherwise false.
*/
public function isRunning(): bool
{
return null !== $this->pipe && $this->pipe->isOpen();
}
/**
* 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.
* @throws \Icicle\Stream\Exception\FailureException If creating a socket pair fails.
*/
public function start()
{
if (0 !== $this->oid) {
throw new StatusError('The thread has already been started.');
}
$this->oid = getmypid();
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 ChannelledStream($this->pipe = new DuplexPipe($channel));
}
/**
* Immediately kills the context.
*
* @throws ThreadException If killing the thread was unsuccessful.
*/
public function kill()
{
if (null !== $this->thread) {
try {
if ($this->thread->isRunning() && !$this->thread->kill()) {
throw new ThreadException('Could not kill thread.');
}
} finally {
$this->close();
}
}
}
/**
* 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);
}
$this->thread = null;
$this->channel = null;
}
/**
* @coroutine
*
* Gets a promise that resolves when the context ends and joins with the
* parent context.
*
* @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.
* @throws SynchronizationError Thrown if an exit status object is not received.
*/
public function join(): \Generator
{
if (null === $this->channel || null === $this->thread) {
throw new StatusError('The thread has not been started or has already finished.');
}
try {
$response = yield from $this->channel->receive();
if (!$response instanceof ExitStatus) {
throw new SynchronizationError('Did not receive an exit status from thread.');
}
$result = $response->getResult();
$this->thread->join();
} catch (\Throwable $exception) {
$this->kill();
throw $exception;
}
$this->close();
return $result;
}
/**
* {@inheritdoc}
*/
public function receive(): \Generator
{
if (null === $this->channel) {
throw new StatusError('The thread has not been started or has already finished.');
}
$data = yield from $this->channel->receive();
if ($data instanceof ExitStatus) {
$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)
));
}
return $data;
}
/**
* {@inheritdoc}
*/
public function send($data): \Generator
{
if (null === $this->channel) {
throw new StatusError('The thread has not been started or has already finished.');
}
if ($data instanceof ExitStatus) {
$this->kill();
throw new InvalidArgumentError('Cannot send exit status objects.');
}
return yield from $this->channel->send($data);
}
}