forked from amal/AzaThread
-
Notifications
You must be signed in to change notification settings - Fork 4
/
ThreadPool.php
914 lines (780 loc) · 17.7 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
<?php
namespace Aza\Components\Thread;
use Aza\Components\CliBase\Base;
use Aza\Components\LibEvent\EventBase;
use Aza\Components\Log\Logger;
use Aza\Components\Thread\Exceptions\Exception;
use Aza\Kernel\Core;
/**
* AzaThread pool.
*
* Old name - CThread.
*
* @project Anizoptera CMF
* @package system.thread
* @author Amal Samally <amal.samally at gmail.com>
* @license MIT
*/
class ThreadPool
{
/**
* Default pool name
*/
const DEFAULT_NAME = 'base';
/**
* All created pools count
*
* @var int
*/
protected static $allPoolsCount = 0;
#region Internal properties
/**
* Maximum threads number in pool
*/
protected $maxThreads = 4;
/**
* Internal unique pool id
*
* @var int
*/
protected $id;
/**
* Internal pool name
*
* @var string
*/
protected $poolName;
/**
* Thread class name
*
* @var string
*/
protected $threadClassName;
/**
* Thread process name
*
* @var null|string
*/
protected $threadProcessName;
/**
* Event listeners
*/
protected $listeners = array();
/**
* Threads in pool (threadId => thread)
*
* @var Thread[]
*/
protected $threads = array();
/**
* Waiting for job threads IDs (threadId => threadId)
*
* @var int[]
*/
protected $waitingForJob = array();
/**
* Waiting for result fetch threads IDs (threadId => threadId)
*
* @var int[]
*/
protected $waitingForFetch = array();
/**
* Working threads IDs (threadId => threadId)
*
* @var int[]
*/
protected $working = array();
/**
* Initializing threads IDs (threadId => threadId)
*
* @var int[]
*/
protected $initializing = array();
/**
* Failed threads IDs (threadId => [errorCode, errorMsg])
*
* @var array[]
*/
protected $failures = array();
/**
* Results flags (threadId => threadId)
*/
protected $resultFlags = array();
/**
* Received results (threadId => result)
*/
protected $results = array();
/**
* Current threads count
*/
protected $threadsCount = 0;
/**
* Flag for detached state.
* Enabled in child process after forking.
*/
protected $detached = false;
/**
* Whether to show debugging information.
* DO NOT USE IN PRODUCTION!
*
* @internal
*/
public $debug = false;
#endregion
#region Initialization
/**
* Thread pool initialization
*
* @param string $threadName Thread class name
* @param int $maxThreads Maximum threads number in pool
* @param string $pName Thread process name
* @param string $name Pool name
* @param bool $debug Whether to enable debug mode
*
* @internal
*/
public function __construct($threadName, $maxThreads = null,
$pName = null, $name = null, $debug = false)
{
$debug && $this->debug = true;
$this->id = ++self::$allPoolsCount;
$this->poolName = $name ?: self::DEFAULT_NAME;
$this->threadClassName = $threadName;
// @codeCoverageIgnoreStart
$this->debug(
"Pool of '$threadName' threads created ("
. ltrim(spl_object_hash($this), '0') . ')'
);
// @codeCoverageIgnoreEnd
if (Thread::$useForks) {
if ($maxThreads > 0) {
$this->maxThreads = (int)$maxThreads;
}
} else {
$this->maxThreads = 1;
}
if ($pName) {
$this->threadProcessName = $pName;
}
$this->createAllThreads();
}
/**
* Creates threads while pool has free slots
*/
protected function createAllThreads()
{
$count = &$this->threadsCount;
$tMax = $this->maxThreads;
if ($count < $tMax) {
$tName = $this->threadClassName;
$pName = $this->threadProcessName;
$debug = $this->debug;
do {
/** @var $thread Thread */
$thread = new $tName($pName, $this, $debug);
$count++;
// @codeCoverageIgnoreStart
$debug && $this->debug(
"Thread #{$thread->getId()} created"
);
// @codeCoverageIgnoreEnd
} while ($count < $tMax);
}
}
#endregion
#region Cleanup
/**
* Destruction
*
* @internal
*/
public function __destruct()
{
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
'Destructor (' . ltrim(spl_object_hash($this), '0') . ')'
);
// @codeCoverageIgnoreEnd
$this->cleanup();
}
/**
* Pool cleanup
*/
public function cleanup()
{
// @codeCoverageIgnoreStart
($debug = $this->debug) && $this->debug(
'Cleanup (' . ltrim(spl_object_hash($this), '0') . ')'
. ($this->detached ? ' (FORCED - redundant instance)' : '')
);
// @codeCoverageIgnoreEnd
// Destroy all threads
if (!$this->detached) {
foreach ($this->threads as $thread) {
$thread->cleanup();
}
}
// Clean all array fields in pool
$this->listeners =
$this->threads =
$this->waitingForJob =
$this->waitingForFetch =
$this->working =
$this->initializing =
$this->failures =
$this->results = array();
}
/**
* Pool detaching (special cleanup
* for pool instance in child process)
*
* @internal
*
* @codeCoverageIgnore Called only in child (can't get coverage from another process)
*/
public function detach()
{
if (!$this->detached) {
$this->detached = true;
$this->cleanup();
$this->debug && $this->debug(
"Thread pool is detached"
);
} else {
$this->debug && $this->debug(
"Thread pool is already detached"
);
}
}
#endregion
/**
* Starts job in one of the idle threads
*
* @see hasWaiting
* @see wait
*
* @return int ID of thread that started the job
*
* @throws Exception if no free threads in pool
*/
public function run()
{
if ($waiting = $this->waitingForJob) {
$threadId = reset($waiting);
$thread = $this->threads[$threadId];
// @codeCoverageIgnoreStart
($debug = $this->debug) && $this->debug(
"Starting job in thread #{$threadId}..."
);
// @codeCoverageIgnoreEnd
// Use strict call for speedup
// if number of arguments is not too big
$args = func_get_args();
$count = count($args);
if (0 === $count) {
$thread->run();
} else if (1 === $count) {
$thread->run($args[0]);
} else if (2 === $count) {
$thread->run($args[0], $args[1]);
} else if (3 === $count) {
$thread->run($args[0], $args[1], $args[2]);
} else {
call_user_func_array(array($thread, 'run'), $args);
}
// @codeCoverageIgnoreStart
$debug && $this->debug(
"Thread #$threadId started"
);
// @codeCoverageIgnoreEnd
return $threadId;
}
// Strict approach
throw new Exception('No threads waiting for the job');
}
#region Master waiting
/**
* Waits for waiting threads in pool
*
* @param array $failed Array of failed threads
*
* @return array Returns array of results (can be empty)
*
* @throws Exception
*/
public function wait(&$failed = null)
{
if ($this->waitingForFetch) {
return $this->getResults($failed);
}
$threadIds = $this->working + $this->initializing;
if ($threadIds) {
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
'Waiting for threads: #' . join(', #', $threadIds)
);
// @codeCoverageIgnoreEnd
Thread::waitThreads($threadIds);
} else {
// Should not be called
// @codeCoverageIgnoreStart
throw new Exception(
'Nothing to wait in pool'
);
// @codeCoverageIgnoreEnd
}
return $this->getResults($failed);
}
/**
* Returns array of results by threads
*
* @param array &$failed Array of failed threads
*
* @return array
*/
protected function getResults(&$failed = null)
{
$results = $this->results;
$failed = $this->failures;
$this->waitingForJob += $this->waitingForFetch;
// @codeCoverageIgnoreStart
if ($this->debug) {
$this->debug(
$results
? 'Fetching results for threads: #'
. join(', #', array_keys($results))
: "No results to return"
);
$failed && $this->debug(
'Fetching FAILED results for threads: #'
. join(', #', array_keys($failed))
);
foreach ($this->waitingForFetch as $threadId) {
$this->debug(
"Thread #{$threadId} is marked as waiting for job"
);
}
}
// @codeCoverageIgnoreEnd
$this->results =
$this->resultFlags =
$this->failures =
$this->waitingForFetch = array();
return $results;
}
#endregion
#region Thread events dispatching
/**
* 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);
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
"New listener binded on event [$event]"
);
// @codeCoverageIgnoreEnd
}
/**
* 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)
{
// @codeCoverageIgnoreStart
($debug = $this->debug) && $this->debug(
"Triggering event \"$event\" on pool"
);
// @codeCoverageIgnoreEnd
if (!empty($this->listeners[$event])) {
// @codeCoverageIgnoreStart
$debug && $this->debug(
"Pool has event listeners. Notify them..."
);
// @codeCoverageIgnoreEnd
/** @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
);
}
}
}
}
#endregion
#region Getters/Setters
/**
* Returns if pool has waiting threads
*
* @return bool
*/
public function hasWaiting()
{
return (bool)$this->waitingForJob;
}
/**
* Returns internal unique pool id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Returns internal pool name
*
* @return string
*/
public function getPoolName()
{
return $this->poolName;
}
/**
* Returns thread process name
*
* @return null|string
*/
public function getThreadProcessName()
{
return $this->threadProcessName;
}
/**
* Returns thread class name
*
* @return string
*/
public function getThreadClassName()
{
return $this->threadClassName;
}
/**
* Returns pool threads
*
* @return Thread[] array of threads (threadId => thread)
*/
public function getThreads()
{
return $this->threads;
}
/**
* Returns status of all threads in pool
*
* @return string[] Array of statuses (threadId => stateName)
*/
public function getThreadsState()
{
$state = array();
foreach ($this->threads as $threadId => $thread) {
$state[$threadId] = $thread->getStateName();
}
return $state;
}
/**
* Returns statistic for all threads in pool
*
* @return array[] Array of data (threadId => data array)
* with fields: state, started_jobs, successful_jobs, failed_jobs
*/
public function getThreadsStatistic()
{
$state = array();
foreach ($this->threads as $threadId => $thread) {
$state[$threadId] = array(
'state' => $thread->getStateName(),
'started_jobs' => $thread->getStartedJobs(),
'successful_jobs' => $thread->getSuccessfulJobs(),
'failed_jobs' => $thread->getFailedJobs(),
);
}
return $state;
}
/**
* Returns current threads count
*/
public function getThreadsCount()
{
return $this->threadsCount;
}
/**
* Returns maximum threads number in pool.
*
* You can increase this number with
* {@link setMaxThreads}, but not decrease
*
* @see setMaxThreads
*
* @return int
*/
public function getMaxThreads()
{
return $this->maxThreads;
}
/**
* Sets maximum threads number
*
* @param int $value
*/
public function setMaxThreads($value)
{
// Filter value
if ($value < $this->threadsCount) {
$value = $this->threadsCount;
} else if (!Thread::$useForks || $value < 1) {
$value = 1;
} else {
$value = (int)$value;
}
// Apply new value
if ($value !== $this->maxThreads) {
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
"The number of threads changed: "
. "{$this->maxThreads} => $value"
);
// @codeCoverageIgnoreEnd
$this->maxThreads = (int)$value;
$this->createAllThreads();
}
}
#endregion
#region Internal API for usage from threads
/**
* Registers thread in pool
*
* @param Thread $thread
*
* @internal
*/
public function registerThread($thread)
{
$this->threads[$thread->getId()] = $thread;
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
"Thread #{$thread->getId()} registered in pool"
);
// @codeCoverageIgnoreEnd
}
/**
* Unregisters thread in pool
*
* @param int $threadId
*
* @internal
*/
public function unregisterThread($threadId)
{
if (isset($this->threads[$threadId])) {
unset(
$this->threads[$threadId],
$this->waitingForJob[$threadId],
$this->working[$threadId],
$this->initializing[$threadId]
);
$this->threadsCount--;
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
"Thread #{$threadId} removed from pool"
);
// @codeCoverageIgnoreEnd
}
}
/**
* Sets processing result from thread
*
* @param int $threadId
* @param mixed $result
*
* @throws Exception
*
* @internal
*/
public function setResultForThread($threadId, $result)
{
if (empty($this->working[$threadId])) {
// @codeCoverageIgnoreStart
// Should not be called
// Break event loop to avoid freezes and other bugs
$base = isset($this->threads[$threadId])
? $this->threads[$threadId]->getEventLoop()
: EventBase::getMainLoop(false);
$base && $base->loopBreak();
throw new Exception("Incorrect thread for result #$threadId");
// @codeCoverageIgnoreEnd
}
$this->results[$threadId] = $result;
$this->resultFlags[$threadId] = $threadId;
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
"Received result from thread #{$threadId}"
);
// @codeCoverageIgnoreEnd
}
/**
* Marks thread as waiting for job
*
* @param int $threadId
* @param int $errorCode
* @param string $errorMsg
*
* @throws Exception
*
* @internal
*/
public function markThreadWaiting($threadId, $errorCode = null, $errorMsg = null)
{
// Working thread
if (isset($this->working[$threadId])) {
if (empty($this->resultFlags[$threadId])) {
$this->failures[$threadId] = array($errorCode, $errorMsg);
// @codeCoverageIgnoreStart
$e = new Exception();
$this->debug && $this->debug(
"Received fail from thread #{$threadId}: "
."Error $errorCode - $errorMsg"
);
// @codeCoverageIgnoreEnd
}
unset($this->working[$threadId]);
$this->waitingForFetch[$threadId] = $threadId;
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
"Thread #{$threadId} is marked as waiting for results fetching"
);
// @codeCoverageIgnoreEnd
return;
}
// Skipping.. async fail
else if (isset($this->waitingForFetch[$threadId])
|| isset($this->waitingForJob[$threadId])
) {
return;
}
// Initializing thread
else if (isset($this->initializing[$threadId])) {
unset($this->initializing[$threadId]);
$this->waitingForJob[$threadId] = $threadId;
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
"Thread #{$threadId} is marked as waiting for job"
);
// @codeCoverageIgnoreEnd
return;
}
// @codeCoverageIgnoreStart
// Incorrect thread - should not be called
// Break event loop to avoid freezes and other bugs
$base = isset($this->threads[$threadId])
? $this->threads[$threadId]->getEventLoop()
: EventBase::getMainLoop(false);
$base && $base->loopBreak();
throw new Exception(
"Incorrect (not working) thread for waiting for the job #$threadId"
);
// @codeCoverageIgnoreEnd
}
/**
* Marks thread as waiting for job
*
* @param int $threadId
*
* @throws Exception
*
* @internal
*/
public function markThreadWorking($threadId)
{
if (empty($this->waitingForJob[$threadId])) {
// @codeCoverageIgnoreStart
// Should not be called
// Break event loop to avoid freezes and other bugs
$base = isset($this->threads[$threadId])
? $this->threads[$threadId]->getEventLoop()
: EventBase::getMainLoop(false);
$base && $base->loopBreak();
throw new Exception("Incorrect thread for working #$threadId");
// @codeCoverageIgnoreEnd
}
unset($this->waitingForJob[$threadId]);
$this->working[$threadId] = $threadId;
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
"Thread #{$threadId} is marked as working"
);
// @codeCoverageIgnoreEnd
}
/**
* Marks thread as initializing
*
* @param int $threadId
*
* @internal
*/
public function markThreadInitializing($threadId)
{
$this->initializing[$threadId] = $threadId;
// @codeCoverageIgnoreStart
$this->debug && $this->debug(
"Thread #{$threadId} is marked as initializing"
);
// @codeCoverageIgnoreEnd
}
#endregion
/**
* Debug logging
*
* @param string $message
*/
protected function debug($message)
{
if (!$this->debug) {
return;
}
$time = Base::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
) {
// @codeCoverageIgnoreStart
// TODO: Event dispatcher call for debug message?
$app->msg($message, Logger::LVL_DEBUG);
} else {
// @codeCoverageIgnoreEnd
echo preg_replace(
'~<(?:/?[a-z][a-z0-9_=;-]+|/)>~Si', '', $message
) . PHP_EOL;
@ob_flush();
@flush();
}
}
}