This repository has been archived by the owner on Apr 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
ThreadPool.php
395 lines (350 loc) · 7.49 KB
/
ThreadPool.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
<?php
namespace Aza\Components\Thread;
use Aza\Components\Cli\Daemons\Daemon;
use Aza\Components\Log\Logger;
use Aza\Components\Thread\Exceptions\Exception;
use Aza\Kernel\Core;
/**
* Thread pool for AzaThread (old name - CThread).
*
* @project Anizoptera CMF
* @package system.thread
* @author Amal Samally <amal.samally at gmail.com>
* @license MIT
*/
class ThreadPool
{
/**
* All started pools count
*
* @var int
*/
protected static $allPoolsCount = 0;
/**
* Maximum threads number in pool
*/
protected $maxThreads = 4;
/**
* Internal pool/thread id
*
* @var int
*/
protected $id;
/**
* Current pool name
*/
protected $poolName;
/**
* Thread name
*/
protected $tName;
/**
* Thread process name
*/
protected $pName;
/**
* Waiting number
*/
protected $waitNumber;
/**
* Event listeners
*/
protected $listeners = array();
/**
* Threads in pool (id => thread)
*
* @var Thread[]
*/
public $threads = array();
/**
* Waiting threads IDs (id => id)
*
* @var int[]
*/
public $waiting = array();
/**
* Working threads IDs (id => id)
*
* @var int[]
*/
public $working = array();
/**
* Initializing threads IDs (id => id)
*
* @var int[]
*/
public $initializing = array();
/**
* Failed threads IDs (id => id)
*
* @var int[]
*/
public $failed = array();
/**
* Received results (id => result)
*/
public $results = array();
/**
* Current threads count
*/
public $threadsCount = 0;
/**
* Whether to show debugging information
*
* @var bool
*/
public $debug = false;
/**
* Thread pool initialization
*
* @param string $threadName Thread class name
* @param int $maxThreads Maximum threads number in pool
* @param string $pName Thread process name
* @param bool $debug Whether to enable debug mode
* @param string $name Pool name
*/
public function __construct($threadName, $maxThreads = null,
$pName = null, $debug = false, $name = 'base')
{
$debug && $this->debug = true;
$this->id = ++self::$allPoolsCount;
$this->poolName = $name;
$this->tName = $threadName;
!Thread::$useForks && $this->maxThreads = 1;
isset($maxThreads) && $this->setMaxThreads($maxThreads);
isset($pName) && $this->pName = $pName;
$this->debug(
"Pool of '$threadName' threads created."
);
$this->createAllThreads();
}
/**
* Destruction
*/
public function __destruct()
{
$this->debug('Destructor');
$this->cleanup();
}
/**
* Pool cleanup
*/
public function cleanup()
{
$this->debug('Cleanup');
foreach ($this->threads as $thread) {
$thread->cleanup();
}
}
/**
* Creates threads while has free slots
*/
protected function createAllThreads()
{
if (($count = &$this->threadsCount) < ($tMax = $this->maxThreads)) {
do {
/** @var $thread Thread */
$thread = $this->tName;
$thread = new $thread($this->debug, $this->pName, $this);
$id = $thread->getId();
$this->threads[$id] = $thread;
$count++;
$this->debug("Thread #$id created");
} while ($count < $tMax);
}
}
/**
* Starts one of free threads
*
* @return int|bool Thread ID or FALSE of no free threads in pool
*/
public function run()
{
$this->createAllThreads();
if ($this->hasWaiting()) {
$threadId = reset($this->waiting);
$thread = $this->threads[$threadId];
$args = func_get_args();
if (($count = count($args)) === 0) {
$thread->run();
} else if ($count === 1) {
$thread->run($args[0]);
} else if ($count === 2) {
$thread->run($args[0], $args[1]);
} else if ($count === 3) {
$thread->run($args[0], $args[1], $args[2]);
} else {
call_user_func_array(array($thread, 'run'), $args);
}
$this->waitNumber--;
$this->debug("Thread #$threadId started");
return $threadId;
}
return false;
}
/**
* Waits for waiting threads in pool
*
* @param array $failed Array of failed threads
*
* @return array|bool Returns array of results or FALSE if no results
*
* @throws Exception
*/
public function wait(&$failed = null)
{
$this->waitNumber = null;
if ($this->results || $this->failed) {
return $this->getResults($failed);
}
if (($w = $this->working) || $this->initializing) {
if ($this->initializing) {
$w += $this->initializing;
}
$this->debug && $this->debug(
'Waiting for threads: ' . join(', ', $w)
);
Thread::waitThreads($w);
} else {
throw new Exception(
'Nothing to wait in pool'
);
}
return $this->getResults($failed);
}
/**
* Returns if pool has waiting threads
*
* @return bool
*/
public function hasWaiting()
{
if ($this->waitNumber === null && $this->waiting) {
$this->waitNumber = count($this->waiting);
return true;
} else {
return $this->waitNumber > 0;
}
}
/**
* Returns array of results by threads or false
*
* @param array $failed Array of failed threads
*
* @return array|bool
*/
protected function getResults(&$failed = null)
{
if ($res = $this->results) {
$this->results = array();
} else {
$res = false;
}
$failed = $this->failed;
$this->failed = array();
return $res;
}
/**
* Returns state of all threads in pool
*
* @return array
*/
protected function getState()
{
$state = array();
foreach ($this->threads as $threadId => $thread) {
$state[$threadId] = $thread->getStateName();
}
return $state;
}
/**
* Connects a listener to a given event.
*
* @see trigger
*
* @param string $event <p>
* An event name.
* </p>
* @param callback $listener <p>
* Callback to be called when the matching event occurs.
* <br><tt>function(string $event_name, int $thread_id, mixed $event_data, mixed $event_arg){}</tt>
* </p>
* @param mixed $arg <p>
* Additional argument for callback.
* </p>
*/
public function bind($event, $listener, $arg = null)
{
if (!isset($this->listeners[$event])) {
$this->listeners[$event] = array();
}
$this->listeners[$event][] = array($listener, $arg);
$this->debug(
"New listener binded on event [$event]"
);
}
/**
* Notifies all listeners of a given event.
*
* @see bind
*
* @param string $event An event name
* @param int $threadId Id of thread that caused the event
* @param mixed $data Event data for callback
*/
public function trigger($event, $threadId, $data = null)
{
$this->debug("Triggering event [$event]");
if (!empty($this->listeners[$event])) {
/** @var $cb callback */
foreach ($this->listeners[$event] as $l) {
list($cb, $arg) = $l;
if ($cb instanceof \Closure) {
$cb($event, $threadId, $data, $arg);
} else {
call_user_func(
$cb, $event, $threadId, $data, $arg
);
}
}
}
}
/**
* Sets maximum threads number
*
* @param int $value
*/
public function setMaxThreads($value)
{
if ($value < $this->threadsCount) {
$value = $this->threadsCount;
} else if (!Thread::$useForks || $value < 1) {
$value = 1;
}
$this->maxThreads = (int)$value;
}
/**
* Debug logging
*
* @param string $message
*/
protected function debug($message)
{
if (!$this->debug) {
return;
}
$time = Daemon::getTimeForLog();
$poolId = $this->id;
$poolName = $this->poolName;
$pid = posix_getpid();
$message = "<small>{$time} [debug] [P{$poolId}.{$poolName}] "
."#{$pid}:</> <info>{$message}</>";
if (class_exists('Aza\Kernel\Core', false) && $app = Core::$app) {
$app->msg($message, Logger::LVL_DEBUG);
} else {
echo strip_tags($message), PHP_EOL;
@ob_flush();
@flush();
}
}
}