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
/
Thread.php
2233 lines (1952 loc) · 44.6 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
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Aza\Components\Thread;
use Aza\Components\CliBase\Base;
use Aza\Components\LibEvent\Event;
use Aza\Components\LibEvent\EventBase;
use Aza\Components\LibEvent\EventBuffer;
use Aza\Components\Log\Logger;
use Aza\Components\Socket\ASocket;
use Aza\Components\Socket\Socket;
use Aza\Components\Thread\Exceptions\Exception;
use Aza\Kernel\Core;
// TODO: Try yo use ZeroMQ?
// http://toys.lerdorf.com/archives/57-ZeroMQ-+-libevent-in-PHP.html
// http://www.zeromq.org/
// http://www.opennet.ru/opennews/art.shtml?num=27137
// http://api.zeromq.org/2-1:zmq-ipc
// TODO: External signal dispatcher
/**
* AzaThread (old name - CThread).
* Powerfull thread emulation with forks and libevent.
* Can work in synchronious mode without forks for compatibility.
*
* @project Anizoptera CMF
* @package system.thread
* @author Amal Samally <amal.samally at gmail.com>
* @license MIT
*/
abstract class Thread
{
#region Constants
// Thread states
const STATE_TERM = 1;
const STATE_INIT = 2;
const STATE_WAIT = 3;
const STATE_WORK = 4;
// Types of IPC packets
const P_STATE = 0x01;
const P_JOB = 0x02;
const P_EVENT = 0x04;
const P_DATA = 0x08;
const P_SERIAL = 0x10;
// Types of IPC data transfer modes
const IPC_IGBINARY = 1; // Igbinary serialization (8th, 6625 jps)
const IPC_SERIALIZE = 2; // Native PHP serialization (8th, 6501 jps)
// Timer names
const TIMER_BASE = 'thread:base:';
const TIMER_WAIT = 'thread:wait:';
// Debug prefixes
const D_INIT = 'INIT: ';
const D_WARN = 'WARN: ';
const D_INFO = 'INFO: ';
const D_IPC = 'IPC: '; // IPC
const D_CLEAN = 'CLEAN: '; // Cleanup
#endregion
#region Public static settings
/**
* IPC Data transfer mode (see self::IPC_*)
*/
public static $ipcDataMode = self::IPC_SERIALIZE;
/**
* Whether threads will use forks
*/
public static $useForks = false;
#endregion
#region Internal static properties
/**
* All started threads count
*
* @var int
*/
private static $threadsCount = 0;
/**
* All threads
*
* @var Thread[]
*/
private static $threads = array();
/**
* Threads by types
*/
private static $threadsByClasses = array();
/**
* Threads marks by child PIDs (PID => thread id)
*
* @var int[]
*/
private static $threadsByPids = array();
/**
* Array of waiting threads (id => id)
*
* @var int[]
*/
private static $waitingThreads = array();
/**
* Signal events
*
* @var Event[]
*/
private static $eventsSignals = array();
/**
* Event base
*
* @var EventBase
*/
private static $base;
#endregion
#region Internal properties
/**
* Pipes pair (master, worker)
*
* @var ASocket[]
*/
private $pipes;
/**
* Master event
*
* @var EventBuffer
*/
private $masterEvent;
/**
* Master read buffer
*/
private $masterBuffer = '';
/**
* Currently receiving packet in child
*
* @var array|null
*/
private $masterPacket;
/**
* Child event
*
* @var EventBuffer
*/
private $childEvent;
/**
* Child read buffer
*/
private $childBuffer = '';
/**
* Currently receiving packet in child
*
* @var array|null
*/
private $childPacket;
/**
* Timer events names
*
* @var string[]
*/
private $eventsTimers = array();
/**
* Event listeners
*/
private $listeners = array();
/**
* Thread process name (if not empty)
*
* @var bool|string
*/
private $processName = false;
/**
* Thread state
*
* @var int
*/
private $state;
/**
* Whether waiting loop is enabled
*/
private $waiting = false;
/**
* Whether event locking is enabled
*/
private $eventLocking = false;
/**
* Cleaning flag
*/
private $cleaning = false;
#endregion
#region Internal protected properties
/**
* Owner thread pool
*
* @var ThreadPool
*/
protected $pool;
/**
* Internal thread id
*
* @var int
*/
protected $id;
/**
* Current process pid
*
* @var int
*/
protected $pid;
/**
* Parent process pid
*
* @var int
*/
protected $parent_pid;
/**
* Child process pid
*
* @var int
*/
protected $child_pid;
/**
* Whether child is already forked
*/
protected $isForked = false;
/**
* Whether current process is child
*/
protected $isChild = false;
/**
* Arguments for the processing
*/
protected $params = array();
/**
* Last processing result
*/
protected $result;
/**
* The status of the success of the task
*/
protected $success = false;
#endregion
#region Settings. Overwrite on child class to set.
/**
* File for shared memory key generation.
* Thread class file by default.
*/
protected $file;
/**
* Whether the thread will wait for next tasks
*/
protected $multitask = true;
/**
* Whether to listen for signals in master.
* SIGCHLD is always listened.
*/
protected $listenMasterSignals = true;
/**
* Perform pre-fork, to avoid wasting resources later
*/
protected $prefork = true;
/**
* Wait for the preforking child
*/
protected $preforkWait = false;
/**
* Worker initialization timeout (in seconds).
* Set it to less than one, to disable.
*/
protected $timeoutMasterInitWait = 3;
/**
* Maximum master timeout to wait for the job results (in seconds).
* Set it to less than one, to disable.
*/
protected $timeoutMasterResultWait = 5;
/**
* Maximum worker job waiting timeout. After it spawned child will die.
* Set it to less than one, to disable.
*/
protected $timeoutWorkerJobWait = -1;
/**
* Worker interval for master checks (in seconds).
*/
protected $intervalWorkerChecks = 15;
/**
* Maximum worker pipe read size in bytes.
* 128kb by default
*/
protected $childReadSize = 0x20000;
/**
* Maximum master pipe read size in bytes.
* 128kb by default
*/
protected $masterReadSize = 0x20000;
/**
* Whether to show debugging information
*/
public $debug = false;
#endregion
/**
* Initializes base parameters
*
* @throw Exception if can't wait for the preforked thread
*
* @param bool $debug Whether to show debugging information
* @param string $pName Thread worker process name
* @param ThreadPool $pool Thread pool
*/
public function __construct($debug = false, $pName = null, $pool = null)
{
$this->id = $id = ++self::$threadsCount;
$class = get_called_class();
self::$threadsByClasses[$class][$id] =
self::$threads[$id] = $this;
$debug && $this->debug = true;
$pool && $this->pool = $pool;
$pName && $this->processName = $pName;
$this->pid =
$this->parent_pid =
$this->child_pid = posix_getpid();
$this->setState(self::STATE_INIT);
$forks = self::$useForks;
if ($debug = $this->debug) {
$message = 'Thread of type "'.get_called_class().'" created.';
$this->debug(self::D_INIT . $message);
if (!$forks) {
$debug && $this->debug(
self::D_WARN . 'Sync mode (you need Forks and LibEvent support'
.' and CLI sapi to use threads asynchronously)'
);
}
}
// Forks preparing
$base = self::$base;
if ($forks) {
// Init shared master event base
if (!$base) {
self::$base = $base = Base::getEventBase();
$debug && $this->debug(
self::D_INIT . 'Master event base initialized'
);
}
// Master signals
if (!self::$eventsSignals) {
if ($this->listenMasterSignals) {
$this->registerEventSignals();
} else {
$signo = SIGCHLD;
$e = new Event();
$e->setSignal($signo, array(get_called_class(), '_mEvCbSignal'))
->setBase($base)
->add();
self::$eventsSignals[$signo] = $e;
$debug && $this->debug(
self::D_INIT . 'Master SIGCHLD event signal handler initialized'
);
}
}
// Master timer
$timer_name = self::TIMER_BASE . $this->id;
$base->timerAdd(
$timer_name, 0,
array($this, '_mEvCbTimer'),
null, false
);
$this->eventsTimers[] = $timer_name;
$debug && $this->debug(
self::D_INIT . "Master timer ($timer_name) added"
);
}
// On load hook
$this->onLoad();
// Preforking
if ($forks && $this->prefork) {
$debug && $this->debug(self::D_INFO . 'Preforking');
if ($this->forkThread()) {
// Parent
if (($interval = $this->timeoutMasterInitWait) > 0) {
$timer_name = self::TIMER_BASE . $this->id;
$base->timerStart(
$timer_name,
$interval,
self::STATE_INIT
);
$debug && $this->debug(
self::D_INFO . "Master timer ($timer_name) started for INIT ($interval sec)"
);
}
$this->preforkWait && $this->wait();
} else {
// Child
$this->evWorkerLoop(true);
$debug && $this->debug(
self::D_INFO . 'Preforking: end of loop, exiting'
);
$this->shutdown();
}
} else {
$this->setState(self::STATE_WAIT);
}
// On fork hook
$forks || $this->onFork();
}
/**
* Destruction
*/
public function __destruct()
{
$this->debug(self::D_INFO . 'Destructor');
$this->cleanup();
}
/**
* Thread cleanup
*/
public function cleanup()
{
if ($this->cleaning) {
return;
}
$this->cleaning = true;
$this->state = self::STATE_TERM;
($debug = $this->debug) && $this->debug(
self::D_CLEAN . 'Cleanup'
);
$id = $this->id;
$class = get_called_class();
$isMaster = !$this->isChild;
// Threads pool
if ($pool = &$this->pool) {
unset(
$pool->threads[$id],
$pool->waiting[$id],
$pool->working[$id],
$pool->initializing[$id]
);
$pool->threadsCount--;
$this->pool = null;
}
// Child process
$base = self::$base;
if ($isMaster && $this->isForked) {
$this->stopWorker(true);
$debug && $this->debug(
self::D_CLEAN . 'Worker process terminated'
);
// Check for non-triggered events
$base && $base->resource && $base->loop(EVLOOP_NONBLOCK);
}
// Threads storage
unset(self::$threads[$id]);
// Events
if ($base && $base->resource) {
foreach ($this->eventsTimers as $t) {
$base->timerDelete($t);
}
}
if (!$isMaster || !self::$threads) {
foreach (self::$eventsSignals as $ev) {
$ev->free();
}
self::$eventsSignals = array();
}
$this->eventsTimers = array();
$debug && $this->debug(
self::D_CLEAN . 'All events freed'
);
// Master event
if ($this->masterEvent) {
$this->masterEvent->free();
$this->masterEvent = null;
$debug && $this->debug(
self::D_CLEAN . 'Master event freed'
);
}
// Child event
if ($this->childEvent) {
$this->childEvent->free();
$this->childEvent = null;
$debug && $this->debug(
self::D_CLEAN . 'Child event freed'
);
}
// Pipes
if ($this->pipes) {
$this->pipes[1]->close();
// It's already closed after forking
$isMaster && $this->pipes[0]->close();
$this->pipes = null;
$debug && $this->debug(
self::D_CLEAN . 'Pipes destructed'
);
}
// Last master thread cleanup
if ($isMaster && !self::$threads) {
self::$base = null;
}
// Child cleanup
else {
// Event base cleanup
self::$base = null;
Base::cleanEventBase();
}
// Threads storage
unset(self::$threadsByClasses[$class][$id]);
if (empty(self::$threadsByClasses[$class])) {
unset(self::$threadsByClasses[$class]);
}
}
/**
* Thread forking
*
* @throws Exception
*
* @return bool TRUE in parent, FALSE in child
*/
private function forkThread()
{
// Checks
if (!self::$useForks) {
throw new Exception(
"Can't fork thread. Forks are not supported."
);
} else if ($this->isForked) {
throw new Exception(
"Can't fork thread. It is already forked."
);
}
// Worker pipes
$debug = $this->debug;
if (!$this->pipes) {
$this->pipes = Socket::pair();
$debug && $this->debug(
self::D_INIT . 'Pipes initialized'
);
}
// Forking
$debug && $this->debug(
self::D_INIT . 'Forking'
);
$this->isForked = true;
$pid = Base::fork();
// In parent
if ($pid) {
self::$threadsByPids[$pid] = $this->id;
$this->child_pid = $pid;
$debug && $this->debug(
self::D_INIT . "Forked: parent ({$this->pid})"
);
// Master event
if (!$this->masterEvent) {
$this->masterEvent = $ev = new EventBuffer(
$this->pipes[0]->resource,
array($this, '_mEvCbRead'),
null,
function(){}
);
$ev->setBase(self::$base)->setPriority()->enable(EV_READ);
$debug && $this->debug(
self::D_INIT . 'Master event initialized'
);
}
return true;
}
// In child
$this->isChild = true;
$this->pid =
$this->child_pid =
$pid = posix_getpid();
$debug && $this->debug(
self::D_INIT . "Forked: child ($pid)"
);
// Closing master pipe
// It is not needed in the child
$this->pipes[0]->close();
unset($this->pipes[0]);
// Cleanup parent events
$this->eventsTimers = self::$eventsSignals = array();
// Child event
if (!$this->childEvent) {
$this->childEvent = $ev = new EventBuffer(
$this->pipes[1]->resource,
array($this, '_wEvCbRead'),
null,
function(){}
);
$ev->setBase(self::$base)->setPriority()->enable(EV_READ);
$debug && $this->debug(
self::D_INIT . 'Worker event initialized'
);
}
// Process name
if ($name = $this->processName) {
$name .= ' (aza-php): worker';
Base::setProcessTitle($name);
$debug && $this->debug(
self::D_INIT . "Child process name is changed to: $name"
);
}
return false;
}
/**
* Starts processing
*
* @return Thread
*
* @throws Exception
*/
public function run()
{
if (!$this->isWaiting()) {
throw new Exception(
"Can't run thread. It is not in waiting state."
." You need to use 'wait' method on thread instance"
." after each run and before first run if 'preforkWait'"
." property is not overrided to TRUE and you don't use pool."
);
}
($debug = $this->debug) && $this->debug(self::D_INFO . 'Job start');
$this->setState(self::STATE_WORK);
$this->result = null;
$this->success = false;
$args = func_get_args();
// Emulating thread with fork
if (self::$useForks) {
// Thread is alive
if ($this->isAlive()) {
$debug && $this->debug(
self::D_INFO . "Child is already running ({$this->child_pid})"
);
$this->sendPacketToChild(self::P_JOB, $args ?: null);
$this->startMasterWorkTimeout();
}
// Forking
else {
if ($this->forkThread()) {
// Parent
$this->startMasterWorkTimeout();
} else {
// Child
$this->setParams($args);
$res = $this->process();
$this->setResult($res);
$this->multitask && $this->evWorkerLoop();
$debug && $this->debug(
self::D_INFO . 'Simple end of work, exiting'
);
$this->shutdown();
}
}
}
// Forkless compatibility
else {
$this->setParams($args);
$res = $this->process();
$this->setResult($res);
$debug && $this->debug(
self::D_INFO . 'Sync job ended'
);
}
return $this;
}
/**
* Prepares and starts worker event loop
*
* @param bool $setState Set waiting state
*
* @throws Exception
*/
private function evWorkerLoop($setState = false)
{
($debug = $this->debug) && $this->debug(
self::D_INIT . "Preparing worker loop"
);
if (!$this->isChild) {
throw new Exception(
'Can\'t start child loop in parent'
);
}
$this->registerEventSignals();
$base = self::$base;
// Worker timer to check master process
$timer = self::TIMER_BASE;
$timerCb = array($this, '_wEvCbTimer');
($timeout = $this->intervalWorkerChecks) > 0 || $timeout = 15;
$base->timerAdd($timer, $timeout, $timerCb);
$this->eventsTimers[] = $timer;
$debug && $this->debug(
self::D_INIT . "Worker timer ($timer) event initialized "
."and set to $timeout"
);
// Worker wait timer
if (0 < $timeout = $this->timeoutWorkerJobWait) {
$timer = self::TIMER_WAIT;
$base->timerAdd($timer, $timeout, $timerCb);
$this->eventsTimers[] = $timer;
$debug && $this->debug(
self::D_INIT . "Worker wait timer ($timer) event "
."initialized and set to $timeout"
);
}
$setState && $this->setState(self::STATE_WAIT);
$debug && $this->debug(self::D_INFO . 'Loop (worker) start');
$base->loop();
$debug && $this->debug(self::D_INFO . 'Loop (worker) end');
}
#region Methods for overriding!
/**
* Hook called after the thread initialization,
* but before forking!
*/
protected function onLoad() {}
/**
* Hook called after the thread forking (in child process)
*/
protected function onFork() {}
/**
* Main processing.
*
* Use {@link getParam} method to get processing parameters
*
* @return mixed returned result will be available via
* {@link getResult} in the master process
*/
abstract protected function process();
#endregion
#region Master waiting
/**
* Waits until the thread becomes waiting
*
* @throws Exception
*
* @return Thread
*/
public function wait()
{
if (self::$useForks && !$this->isWaiting()) {
$this->debug(
self::D_INFO . 'Loop (master waiting) start'
);
$this->waiting = true;
self::evMasterLoop();
if (!$this->isWaiting()) {
throw new Exception(
'Could not wait for the thread'
);
}
}
return $this;
}
/**
* Waits until one of specified threads becomes waiting
*
* @param int|int[] $threadIds
*/
public static function waitThreads($threadIds)
{
if (self::$useForks && $threadIds) {
self::stDebug(
self::D_INFO . 'Loop (master theads waiting) start'
);
$threadIds = (array)$threadIds;
$threadIds = array_combine($threadIds, $threadIds);
self::$waitingThreads = $threadIds;
self::evMasterLoop();
self::$waitingThreads = array();
}
}
/**
* Starts master event loop
*/
private static function evMasterLoop()
{
if (!$base = self::$base) {
throw new Exception(
"Can't start loop (master). EventBase is cleaned"
);
}
($debug = self::stGetDebug($thread)) && self::stDebug(
self::D_INFO . 'Loop (master) start',
$thread
);
$base->loop();
$debug && self::stDebug(
self::D_INFO . 'Loop (master) end',
$thread
);
}
/**
* Starts master work timeout
*/
private function startMasterWorkTimeout()
{
if (0 < $interval = $this->timeoutMasterResultWait) {
$timer_name = self::TIMER_BASE . $this->id;
self::$base->timerStart(
$timer_name, $interval, self::STATE_WORK
);
$this->debug(
self::D_INFO . "Master timer ($timer_name) "
."started for WORK ($interval sec)"
);
}
}
#endregion
#region Event system
/**
* 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,
* mixed $event_data, mixed $event_arg){}</tt>
* </p>
* @param mixed $arg <p>
* Additional argument for callback.
* </p>
*/
public function bind($event, $listener, $arg = null)
{
// Bind is allowed only in parent
if (!$this->isChild) {
if (!isset($this->listeners[$event])) {
$this->listeners[$event] = array();
}
$this->listeners[$event][] = array($listener, $arg);
$this->debug(
self::D_INFO . "New listener binded on event [$event]"
);
}
}
/**
* Notifies all listeners of a given event.
*
* @see bind
*
* @param string $event An event name
* @param mixed $data Event data for callback
*/
public function trigger($event, $data = null)
{
($debug = $this->debug) && $this->debug(
self::D_INFO . "Triggering event [$event]"
);
// Child
if ($this->isChild) {
$this->sendPacketToParent(
self::P_EVENT, $event, $data
);
if (isset($data) && $this->eventLocking) {
$debug && $this->debug(
self::D_INFO . "Locking thread - waiting "
."for event read confirmation"
);
$this->waiting = true;