-
Notifications
You must be signed in to change notification settings - Fork 5
/
GPhpThread.php
executable file
·2094 lines (1822 loc) · 75 KB
/
GPhpThread.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
/**
* The MIT License (MIT)
*
* Copyright (c) 2024 zhgzhg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author zhgzhg @ github.com
* @version 1.0.6
* @copyright zhgzhg, 2024
*/
// define("DEBUG_MODE", true);
declare(ticks=30);
/**
* Exception thrown by GPhpThreads components
* @api
*/
class GPhpThreadException extends \Exception // {{{
{
/**
* Constructor.
* @param string $msg Exception message.
* @param int $code Exception code number.
* @param Exception $previous The previous exception used for the exception chaining.
*/
public function __construct($msg, $code = 0, \Exception $previous = NULL) {
parent::__construct($msg, $code, $previous);
}
} // }}}
/**
* Process intercommunication class.
* A pipe inter-process communication method is used, based on asynchronous or synchronous communication.
* @api
*/
class GPhpThreadIntercom // {{{
{
/** @internal */
private $commFilePath = '';
/** @internal */
private $commChanFdArr = array();
/** @internal */
private $success = true;
/** @internal */
private $autoDeletion = false;
/** @internal */
private $isReadMode = true;
/** @internal */
private $ownerPid = null;
/**
* Constructor.
* @param string $filePath The file that is going to store the pipe.
* @param bool $isReadMode Indicates if the param is going to be read only
* @param bool $autoDeletion If it is set during the destruction of the GPhpThreadIntercom instance the pipe file will be also removed.
*/
public function __construct($filePath, $isReadMode = true, $autoDeletion=false) { // {{{
$this->ownerPid = getmypid();
if (!file_exists($filePath)) {
if (!posix_mkfifo($filePath, 0644)) {
$this->success = false;
return;
}
}
$commChanFd = fopen($filePath, ($isReadMode ? 'r+' : 'w+')); // + mode makes it non blocking too
if ($commChanFd === false) {
$this->success = false;
return;
}
if (!stream_set_blocking($commChanFd, false)) {
$this->success = false;
fclose($commChanFd);
if ($autoDeletion) @unlink($filePath);
return;
}
$this->commChanFdArr[] = $commChanFd;
$this->commFilePath = $filePath;
$this->autoDeletion = $autoDeletion;
$this->isReadMode = $isReadMode;
} // }}}
/**
* Checks if the intercom is initialized and ready for use.
* @return bool
*/
public function isInitialized() { // {{{
return $this->success;
} // }}}
/**
* Returns the state of the option automatic deletion of the pipe file.
* @return bool
*/
public function getAutoDeletionFlag() { // {{{
return $this->autoDeletion;
} // }}}
/**
* Sets the automatic deletion option for the pipe file during the destruction of current instance.
* @param bool $booleanValue
* @return void
*/
public function setAutoDeletionFlag($booleanValue) { // {{{
$this->autoDeletion = $booleanValue;
} // }}}
/**
* Destructor. May try automatically to delete the pipe file.
*/
public function __destruct() { // {{{
if ($this->success && $this->ownerPid === getmypid()) {
if (isset($this->commChanFdArr[0]) &&
is_resource($this->commChanFdArr[0])) {
fclose($this->commChanFdArr[0]);
}
if ($this->autoDeletion) @unlink($this->commFilePath);
}
} // }}}
/**
* Sends data through the intercom.
* @param string $dataString The data to be sent
* @param int $dataLength The length of the data
* @return bool On success returns true otherwise false is returned.
*/
public function send($dataString, $dataLength) { // {{{
if ($this->success && !$this->isReadMode) {
//if (defined('DEBUG_MODE')) echo $dataString . '[' . getmypid() . "] sending\n";
$data = (string)$dataString;
$read = $except = null;
$commChanFdArr = $this->commChanFdArr;
if (stream_select($read, $commChanFdArr, $except, 1) == 0) return false;
while ($dataLength > 0) {
$bytesWritten = fwrite($this->commChanFdArr[0], $data);
if ($bytesWritten === false) return false;
$dataLength -= $bytesWritten;
if ($dataLength > 0) {
$commChanFdArr = $this->commChanFdArr;
if (stream_select($read, $commChanFdArr, $except, 10) == 0)
return false;
$data = substr($data, 0, $bytesWritten);
}
if (!isset($this->commChanFdArr[0]) || !is_resource($this->commChanFdArr[0])) break;
}
if ($dataLength <= 0) return true;
}
return false;
} // }}}
/**
* Receives data from the intercom.
* @param int $timeout The maximum time period in milliseconds during which to wait for data to arrive.
* @return string|null If there is no data up to 700 ms after the method is called it returns NULL otherwise returns the data string itself.
*/
public function receive($timeout = 700) { // {{{
if (!$this->success || !$this->isReadMode) return false;
if (!isset($this->commChanFdArr[0]) || !is_resource($this->commChanFdArr[0])) return false;
$commChanFdArr = $this->commChanFdArr;
$write = $except = null;
$data = null;
$timeout = abs((int)$timeout);
$timeout *= 1000; // convert us to ms
if (stream_select($commChanFdArr, $write, $except, 0, $timeout) == 0) return $data;
do {
$d = fread($this->commChanFdArr[0], 1);
if ($d !== false) $data .= $d;
if (!isset($this->commChanFdArr[0]) || !is_resource($this->commChanFdArr[0])) break;
$commChanFdArr = $this->commChanFdArr;
} while ($d !== false && stream_select($commChanFdArr, $write, $except, 0, 22000) != 0);
//if (defined('DEBUG_MODE')) echo $data . '[' . getmypid() . "] received\n"; // 4 DEBUGGING
return $data;
} // }}}
/**
* Checks if there is pending data for receiving.
* @return mixed Returns 0 or false if there is no data up to 15 ms after the method is called. Otherwise returns the number of contained stream resources (usually 1).
*/
public function isReceivingDataAvailable() { // {{{
if (!$this->success || !$this->isReadMode) return false;
if (!isset($this->commChanFdArr[0]) || !is_resource($this->commChanFdArr[0])) return false;
$commChanFdArr = $this->commChanFdArr;
$write = null; $except = null;
return (stream_select($commChanFdArr, $write, $except, 0, 15000) != 0);
} // }}}
} // }}}
/**
* Critical section for sharing data between multiple processes.
* It provides a slower data-safe manipulating methods and unsafe faster methods.
* @see \GPhpThreadIntercom \GPhpThreadIntercom is used for synchronization between the different processes.
* @api
*/
class GPhpThreadCriticalSection // {{{
{
/** @internal */
private $uniqueId = 0; // the identifier of a concrete instance
/** @internal */
private static $uniqueIdSeed = 0; // the uniqueId index seed
/** @internal */
private static $instancesCreatedEverAArr = array(); // contain all the instances that were ever created of this class
/** @internal */
private static $threadsForRemovalAArr = array(); // contain all the instances that were terminated; used to make connection with $mastersThreadSpecificData
/** @internal */
private $creatorPid;
/** @internal */
private $pipeDir = '';
/** @internal */
private $ownerPid = false; // the thread PID owning the critical section
/** @internal */
private $myPid; // point of view of the current instance
/** @internal */
private $sharedData = array('rel' => array(), 'unrel' => array()); // variables shared in one CS instance among all threads ; two sections are provided reliable one that requires locking of the critical section and unreliable one that does not require locking
/** @internal */
private $mastersThreadSpecificData = array(); // specific per each thread variables / the host is the master parent
// ======== thread specific variables ========
/** @internal */
private $intercomWrite = null;
/** @internal */
private $intercomRead = null;
/** @internal */
private $intercomInterlocutorPid = null;
/** @internal */
private $dispatchPriority = 0;
// ===========================================
/**
* @internal Special variable used in PHP 5.3 to emulate a context-specific use operator with lambdas
*/
private $bindVariable;
/**
* @internal Special variable used in PHP 5.3 to emulate a context-specific use operator with lambdas
*/
private static $bindStaticVariable;
/** @internal */
private static $ADDORUPDATESYN = '00', $ADDORUPDATEACK = '01', $ADDORUPDATENACK = '02',
$UNRELADDORUPDATESYN = '03', $UNRELADDORUPDATEACK = '04', $UNRELADDORUPDATENACK = '05',
$ERASESYN = '06', $ERASEACK = '07', $ERASENACK = '08',
$UNRELERASESYN = '09', $UNRELERASEACK = '10', $UNRELERASENACK = '11',
$READSYN = '12', $READACK = '13', $READNACK = '14',
$UNRELREADSYN = '15', $UNRELREADACK = '16', $UNRELREADNACK = '17',
$READALLSYN = '18', $READALLACK = '19', $READALLNACK = '20',
$LOCKSYN = '21', $LOCKACK = '22', $LOCKNACK = '23',
$UNLOCKSYN = '24', $UNLOCKACK = '25', $UNLOCKNACK = '26';
/** @internal */
private static $ADDORUPDATEACT = 1, $UNRELADDORUPDATEACT = 2,
$ERASEACT = 3, $UNRELERASEACT = 4,
$READACT = 5, $UNRELREADACT = 6, $READALLACT = 7;
/**
* Constructor.
* @param string $pipeDirectory The directory where the pipe files for the inter-process communication will be stored.
*/
public function __construct($pipeDirectory = '/dev/shm') { // {{{
$this->uniqueId = self::$uniqueIdSeed++;
self::$instancesCreatedEverAArr[$this->uniqueId] = &$this;
$this->creatorPid = getmypid();
$this->pipeDir = rtrim($pipeDirectory, ' /') . '/';
} // }}}
/**
* Destructor.
*/
public function __destruct() { // {{{
$this->intercomRead = null;
$this->intercomWrite = null;
if (self::$instancesCreatedEverAArr !== null)
unset(self::$instancesCreatedEverAArr[$this->uniqueId]);
} // }}}
/**
* Initializes the critical section.
* @param int $afterForkPid The process identifier obtained after the execution of a fork() used to differentiate between different processes - pseudo threads.
* @param int $threadId The internal to the GPhpThread identifier of the current thread instance which is unique identifier in the context of the current process.
* @return bool On success returns true otherwise false.
*/
public function initialize($afterForkPid, $threadId) { // {{{
$this->myPid = getmypid();
$retriesLimit = 60;
if ($this->myPid == $this->creatorPid) { // parent
$i = 0;
do {
$intercomWrite = new GPhpThreadIntercom("{$this->pipeDir}gphpthread_{$this->uniqueId}_s{$this->myPid}-d{$afterForkPid}", false, true);
if ($intercomWrite->isInitialized()) {
$i = $retriesLimit;
} else {
++$i;
usleep(mt_rand(5000, 80000));
}
} while ($i < $retriesLimit);
$i = 0;
do {
$intercomRead = new GPhpThreadIntercom("{$this->pipeDir}gphpthread_{$this->uniqueId}_s{$afterForkPid}-d{$this->myPid}", true, true);
if ($intercomRead->isInitialized()) {
$i = $retriesLimit;
} else {
++$i;
usleep(mt_rand(5000, 80000));
}
} while ($i < $retriesLimit);
if ($intercomWrite->isInitialized() && $intercomRead->isInitialized()) {
$this->mastersThreadSpecificData[$threadId] = array(
'intercomRead' => $intercomRead,
'intercomWrite' => $intercomWrite,
'intercomInterlocutorPid' => $afterForkPid,
'dispatchPriority' => 0
);
return true;
}
return false;
} else { // child
self::$instancesCreatedEverAArr = null; // the child must not know for its neighbours
$this->mastersThreadSpecificData = null; // and any details for the threads inside cs instance simulation
self::$threadsForRemovalAArr = null;
// these point to the same memory location and also become
// aliases of each other which is strange?!?
// so we need to recreate them
unset($this->intercomWrite);
unset($this->intercomRead);
unset($this->intercomInterlocutorPid);
$this->intercomWrite = null;
$this->intercomRead = null;
$this->intercomInterlocutorPid = null;
$this->intercomInterlocutorPid = $this->creatorPid;
$i = 0;
do {
$this->intercomWrite = new GPhpThreadIntercom("{$this->pipeDir}gphpthread_{$this->uniqueId}_s{$this->myPid}-d{$this->creatorPid}", false, true);
if ($this->intercomWrite->isInitialized()) {
$i = $retriesLimit;
} else {
++$i;
usleep(mt_rand(5000, 80000));
}
} while ($i < $retriesLimit);
$i = 0;
do {
$this->intercomRead = new GPhpThreadIntercom("{$this->pipeDir}gphpthread_{$this->uniqueId}_s{$this->creatorPid}-d{$this->myPid}", true, false);
if ($this->intercomRead->isInitialized()) {
$i = $retriesLimit;
} else {
++$i;
usleep(mt_rand(5000, 80000));
}
} while ($i < $retriesLimit);
if (!$this->intercomWrite->isInitialized()) $this->intercomWrite = null;
if (!$this->intercomRead->isInitialized()) $this->intercomRead = null;
if ($this->intercomWrite == null || $this->intercomRead == null) {
$this->intercomInterlocutorPid = null;
return false;
}
return true;
}
return false;
} // }}}
/**
* Cleans pipe files garbage left from any ungracefully terminated instances.
* @return int The total number of unused, cleaned pipe garbage files.
*/
public function cleanPipeGarbage() { // {{{
$i = 0;
$dirFp = @opendir($this->pipeDir);
if ($dirFp !== false) {
while (($fileName = readdir($dirFp)) !== false) {
if ($fileName[0] != '.' && is_file($this->pipeDir . $fileName)) {
if (preg_match("/^gphpthread_\d+_s(\d+)\-d(\d+)$/", $fileName, $matches)) {
if (!posix_kill($matches[1], 0) && !posix_kill($matches[2], 0)) {
if (@unlink($this->pipeDir . $fileName)) {
++$i;
}
}
}
}
}
closedir($dirFp);
}
return $i;
} // }}}
/**
* Finalization of a thread instance that ended and soon will be destroyed.
* @param int $threadId The internal thread identifier.
* @return void
*/
public function finalize($threadId) { // {{{
unset($this->mastersThreadSpecificData[$threadId]);
} // }}}
/**
* Confirms if the current thread has the ownership of the critical section associated with it.
* @return bool
*/
private function doIOwnIt() { // {{{
return ($this->ownerPid !== false && $this->ownerPid == $this->myPid);
} // }}}
/**
* Encodes data in a message that will be sent to the thread process dispatcher.
* @param string $msg The message type identifier.
* @param string $name The variable name whose data is going to be sent.
* @param mixed $value The current value of the desired for sending variable.
* @return string The composed message string
*/
private function encodeMessage($msg, $name, $value) { // {{{
// 2 decimal digits message code, 10 decimal digits PID,
// 4 decimal digits name length, name, data
return $msg . sprintf('%010d%04d', $this->myPid, ($name !== null ? strlen($name) : 0)) . $name . serialize($value);
} // }}}
/**
* Decodes encoded from GPhpThread's instance message.
* @param string $encodedMsg The encoded message
* @param string $msg The encoded message type identifier. REFERENCE type.
* @param int $pid The process id of the sender. REFERENCE type.
* @param string $name The variable name whose data was sent. REFERENCE type.
* @param mixed $value The variable data contained in the encoded message. REFERENCE type.
* @return void
*/
private function decodeMessage($encodedMsg, &$msg, &$pid, &$name, &$value) { // {{{
// 2 decimal digits message code, 10 decimal digits PID,
// 4 decimal digits name length, name, data
$msg = substr($encodedMsg, 0, 2);
$pid = substr($encodedMsg, 2, 10);
$pid = (int)preg_filter("/^0{1,9}/", '', $pid); // make the pid decimal number
$nlength = substr($encodedMsg, 12, 4);
$nlength = (int)preg_filter("/^0{1,3}/", '', $nlength); // make the length decimal number
if ($nlength == 0) $name = null;
else $name = substr($encodedMsg, 16, $nlength);
if (strlen($encodedMsg) > 16) $value = unserialize(substr($encodedMsg, 16 + $nlength));
else $value = null;
} // }}}
/**
* Checks if the internal intercom is broken.
* @return bool Returns true if the intercom is broken otherwise returns false.
*/
private function isIntercomBroken() { // {{{
return (empty($this->intercomWrite) ||
empty($this->intercomRead) ||
empty($this->intercomInterlocutorPid) ||
!$this->isPidAlive($this->intercomInterlocutorPid));
} // }}}
/**
* Sends data operation to the main process dispatcher.
* @param string $operation The operation type code.
* @param string $resourceName The name of resource that is holding a particular data that will be "shared".
* @param mixed $resourceValue The value of the resource.
* @return bool Returns true on success otherwise false.
*/
private function send($operation, $resourceName, $resourceValue) { // {{{
if ($this->isIntercomBroken()) return false;
$isAlive = true;
$msg = $this->encodeMessage($operation, $resourceName, $resourceValue);
if (defined('DEBUG_MODE')) {
$dbgStr = '[' . getmypid() . "] is sending ";
switch ($operation) {
case self::$ADDORUPDATESYN: $dbgStr .= 'ADDORUPDATESYN'; break;
case self::$ADDORUPDATEACK: $dbgStr .= 'ADDORUPDATEACK'; break;
case self::$ADDORUPDATENACK: $dbgStr .= 'ADDORUPDATE_N_ACK'; break;
case self::$UNRELADDORUPDATESYN: $dbgStr .= 'UNRELADDORUPDATESYN'; break;
case self::$UNRELADDORUPDATEACK: $dbgStr .= 'UNRELADDORUPDATEACK'; break;
case self::$UNRELADDORUPDATENACK: $dbgStr .= 'UNRELADDORUPDATE_N_ACK'; break;
case self::$ERASESYN: $dbgStr .= 'ERASESYN'; break;
case self::$ERASEACK: $dbgStr .= 'ERASEACK'; break;
case self::$ERASENACK: $dbgStr .= 'ERASE_N_ACK'; break;
case self::$UNRELERASESYN: $dbgStr .= 'UNRELERASESYN'; break;
case self::$UNRELERASEACK: $dbgStr .= 'UNRELERASEACK'; break;
case self::$UNRELERASENACK: $dbgStr .= 'UNRELERASE_N_ACK'; break;
case self::$READSYN: $dbgStr .= 'READSYN'; break;
case self::$READACK: $dbgStr .= 'READACK'; break;
case self::$READNACK: $dbgStr .= 'READ_N_ACK'; break;
case self::$UNRELREADSYN: $dbgStr .= 'UNRELREADSYN'; break;
case self::$UNRELREADACK: $dbgStr .= 'UNRELREADACK'; break;
case self::$UNRELREADNACK: $dbgStr .= 'UNRELREAD_N_ACK'; break;
case self::$READALLSYN: $dbgStr .= 'READALLSYN'; break;
case self::$READALLACK: $dbgStr .= 'READALLACK'; break;
case self::$READALLNACK: $dbgStr .= 'READALL_N_ACK'; break;
case self::$LOCKSYN: $dbgStr .= 'LOCKSYN'; break;
case self::$LOCKACK: $dbgStr .= 'LOCKACK'; break;
case self::$LOCKNACK: $dbgStr .= 'LOCK_N_ACK'; break;
case self::$UNLOCKSYN: $dbgStr .= 'UNLOCKSYN'; break;
case self::$UNLOCKACK: $dbgStr .= 'UNLOCKACK'; break;
case self::$UNLOCKNACK: $dbgStr .= 'UNLOCK_N_ACK'; break;
}
echo "{$dbgStr}, {$resourceName}, " . serialize($resourceValue) . " to {$this->intercomInterlocutorPid} /// {$msg}\n";
}
do {
$isSent = $this->intercomWrite->send($msg, strlen($msg));
if (!$isSent) {
$isAlive = $this->isPidAlive($this->intercomInterlocutorPid);
if ($isAlive) {
for ($i = 0; $i < 120; ++$i) { }
usleep(mt_rand(10000, 200000));
}
}
} while ((!$isSent) && $isAlive);
return $isSent;
} // }}}
/**
* Receives data operation from the main process dispatcher.
* @param string $message The operation type code. REFERENCE type.
* @param int $pid The process id of the sender "thread". REFERENCE type.
* @param string $resourceName The name of resource that is holding a particular data that will be "shared". REFERENCE type.
* @param mixed $resourceValue The value of the resource. REFERENCE type.
* @param int $timeInterval Internal wait time interval in milliseconds between each data check.
* @return bool Returns true on success otherwise false.
*/
private function receive(&$message, &$pid, &$resourceName, &$resourceValue, $timeInterval = 700) { // {{{
if ($this->isIntercomBroken()) return false;
$data = null;
$isAlive = true;
do {
$data = $this->intercomRead->receive($timeInterval);
$isDataEmpty = empty($data);
if ($isDataEmpty) {
$isAlive = $this->isPidAlive($this->intercomInterlocutorPid);
if ($isAlive) {
for ($i = 0; $i < 120; ++$i) { }
usleep(mt_rand(10000, 200000));
}
}
} while ($isDataEmpty && $isAlive);
if (!$isDataEmpty)
$this->decodeMessage($data, $message, $pid, $resourceName, $resourceValue);
if (defined('DEBUG_MODE')) {
$dbgStr = '[' . getmypid() . "] received ";
switch ($message) {
case self::$ADDORUPDATESYN: $dbgStr .= 'ADDORUPDATESYN'; break;
case self::$ADDORUPDATEACK: $dbgStr .= 'ADDORUPDATEACK'; break;
case self::$ADDORUPDATENACK: $dbgStr .= 'ADDORUPDATE_N_ACK'; break;
case self::$UNRELADDORUPDATESYN: $dbgStr .= 'UNRELADDORUPDATESYN'; break;
case self::$UNRELADDORUPDATEACK: $dbgStr .= 'UNRELADDORUPDATEACK'; break;
case self::$UNRELADDORUPDATENACK: $dbgStr .= 'UNRELADDORUPDATE_N_ACK'; break;
case self::$ERASESYN: $dbgStr .= 'ERASESYN'; break;
case self::$ERASEACK: $dbgStr .= 'ERASEACK'; break;
case self::$ERASENACK: $dbgStr .= 'ERASE_N_ACK'; break;
case self::$UNRELERASESYN: $dbgStr .= 'UNRELERASESYN'; break;
case self::$UNRELERASEACK: $dbgStr .= 'UNRELERASEACK'; break;
case self::$UNRELERASENACK: $dbgStr .= 'UNRELERASE_N_ACK'; break;
case self::$READSYN: $dbgStr .= 'READSYN'; break;
case self::$READACK: $dbgStr .= 'READACK'; break;
case self::$READNACK: $dbgStr .= 'READ_N_ACK'; break;
case self::$UNRELREADSYN: $dbgStr .= 'UNRELREADSYN'; break;
case self::$UNRELREADACK: $dbgStr .= 'UNRELREADACK'; break;
case self::$UNRELREADNACK: $dbgStr .= 'UNRELREAD_N_ACK'; break;
case self::$READALLSYN: $dbgStr .= 'READALLSYN'; break;
case self::$READALLACK: $dbgStr .= 'READALLACK'; break;
case self::$READALLNACK: $dbgStr .= 'READALL_N_ACK'; break;
case self::$LOCKSYN: $dbgStr .= 'LOCKSYN'; break;
case self::$LOCKACK: $dbgStr .= 'LOCKACK'; break;
case self::$LOCKNACK: $dbgStr .= 'LOCK_N_ACK'; break;
case self::$UNLOCKSYN: $dbgStr .= 'UNLOCKSYN'; break;
case self::$UNLOCKACK: $dbgStr .= 'UNLOCKACK'; break;
case self::$UNLOCKNACK: $dbgStr .= 'UNLOCK_N_ACK'; break;
}
echo "{$dbgStr}, {$resourceName}, " . serialize($resourceValue) . " from {$pid} /// {$data}\n";
}
return !$isDataEmpty;
} // }}}
/**
* Tries to lock the critical section.
* @return bool Returns true on success otherwise false.
*/
private function requestLock() { // {{{
$msg = $pid = $name = $value = null;
if (!$this->send(self::$LOCKSYN, $name, $value)) return false;
if (!$this->receive($msg, $pid, $name, $value)) return false;
if ($msg != self::$LOCKACK)
return false;
$this->ownerPid = $this->myPid;
return true;
} // }}}
/**
* Tries to unlock the critical section.
* @return bool Returns true on success otherwise false.
*/
private function requestUnlock() { // {{{
$msg = $pid = $name = $value = null;
if (!$this->send(self::$UNLOCKSYN, $name, $value))
return false;
if (!$this->receive($msg, $pid, $name, $value))
return false;
if ($msg != self::$UNLOCKACK)
return false;
$this->ownerPid = false;
return true;
} // }}}
/**
* Executes data operation on the internal shared data container.
* @param string $actionType The performed operation code.
* @param string $name The name of the resource.
* @param mixed $value The value of the resource.
* @return bool Returns true on success otherwise false.
*/
private function updateDataContainer($actionType, $name, $value) { // {{{
$result = false;
$msg = null;
$pid = null;
switch ($actionType) {
case self::$ADDORUPDATEACT:
if ($name === null || $name === '') break;
if (!$this->send(self::$ADDORUPDATESYN, $name, $value)) break;
if (!$this->receive($msg, $pid, $name, $value)) break;
if ($msg == self::$ADDORUPDATEACK) {
$result = true;
$this->sharedData['rel'][$name] = $value;
}
break;
case self::$UNRELADDORUPDATEACT:
if ($name === null || $name === '') break;
if (!$this->send(self::$UNRELADDORUPDATESYN, $name, $value)) break;
if (!$this->receive($msg, $pid, $name, $value)) break;
if ($msg == self::$UNRELADDORUPDATEACK) {
$result = true;
$this->sharedData['unrel'][$name] = $value;
}
break;
case self::$ERASEACT:
if ($name === null || $name === '') break;
if (!$this->send(self::$ERASESYN, $name, $value)) break;
if (!$this->receive($msg, $pid, $name, $value)) break;
if ($msg == self::$ERASEACK) {
$result = true;
unset($this->sharedData['rel'][$name]);
}
break;
case self::$UNRELERASEACT:
if ($name === null || $name === '') break;
if (!$this->send(self::$UNRELERASESYN, $name, $value)) break;
if (!$this->receive($msg, $pid, $name, $value)) break;
if ($msg == self::$UNRELERASEACK) {
$result = true;
unset($this->sharedData['unrel'][$name]);
}
break;
case self::$READACT:
if ($name === null || $name === '') break;
if (!$this->send(self::$READSYN, $name, $value)) break;
if (!$this->receive($msg, $pid, $name, $value)) break;
if ($msg == self::$READACK) {
$result = true;
$this->sharedData['rel'][$name] = $value;
}
break;
case self::$UNRELREADACT:
if ($name === null || $name === '') break;
if (!$this->send(self::$UNRELREADSYN, $name, $value)) break;
if (!$this->receive($msg, $pid, $name, $value)) break;
if ($msg == self::$UNRELREADACK) {
$result = true;
$this->sharedData['unrel'][$name] = $value;
}
break;
case self::$READALLACT:
if (!$this->send(self::$READALLSYN, $name, $value)) break;
if (!$this->receive($msg, $pid, $name, $value)) break;
if ($msg == self::$READALLACK) {
$result = true;
$this->sharedData = $value;
}
break;
}
return $result;
} // }}}
/**
* Checks if specific process id is still alive.
* @param int $pid The process identifier.
* @return bool Returns true if the pid is alive otherwise returns false.
*/
private function isPidAlive($pid) { // {{{
if ($pid === false) return false;
return posix_kill($pid, 0);
} // }}}
/**
* Sort by occurred lock and dispatch priority. This is a workaround
* method required for PHP 5.3 and relies on an initialized
* $bindVariable inside this class.
* @param mixed $a The first key to be taken into account.
* @param mixed $b The second key to be taken into account.
* @return int -1, 0 or 1 depending on which key is more preferable.
*/
private function sortByLockAndDispatchPriority($a, $b) { // {{{
$presentIndexA = false;
if (isset($this->bindVariable->mastersThreadSpecificData[$a])) {
if ($this->bindVariable->mastersThreadSpecificData[$a]['intercomInterlocutorPid'] === $this->bindVariable->ownerPid) return -1;
$presentIndexA = true;
}
$presentIndexB = false;
if (isset($this->bindVariable->mastersThreadSpecificData[$b])) {
if ($this->bindVariable->mastersThreadSpecificData[$b]['intercomInterlocutorPid'] === $this->bindVariable->ownerPid) return 1;
$presentIndexB = true;
}
if (!($presentIndexA && $presentIndexB)) {
return ($presentIndexA ? -1 : (int)$presentIndexB);
}
return (int)($this->bindVariable->mastersThreadSpecificData[$a]['dispatchPriority'] < $this->bindVariable->mastersThreadSpecificData[$b]['dispatchPriority']);
} // }}}
/**
* Sort by occurred lock, dispatch priority and most threads using
* the critical section. This is workaround method required for
* PHP 5.3 and relies on an initialized $bindVariable inside this
* class.
* @param mixed $a The first key to be taken into account.
* @param mixed $b The second key to be taken into account.
* @return int -1, 0 or 1 depending on which key is more preferable.
*/
private static function sortByLockDispatchPriorityAndMostThreadsInside($a, $b) { // {{{
// the locker thread is with highest priority
if (self::$bindStaticVariable[$a]->mastersThreadSpecificData['intercomInterlocutorPid'] == self::$bindStaticVariable[$a]->ownerPid) return -1;
if (self::$bindStaticVariable[$b]->mastersThreadSpecificData['intercomInterlocutorPid'] == self::$bindStaticVariable[$b]->ownerPid) return 1;
// deal with the case of critical sections with no threads
if (!empty(self::$bindStaticVariable[$a]->mastersThreadSpecificData) && empty(self::$bindStaticVariable[$b]->mastersThreadSpecificData)) { return -1; } // a
else if (empty(self::$bindStaticVariable[$a]->mastersThreadSpecificData) && !empty(self::$bindStaticVariable[$b]->mastersThreadSpecificData)) { return 1; } // b
else if (empty(self::$bindStaticVariable[$b]->mastersThreadSpecificData) && empty(self::$bindStaticVariable[$b]->mastersThreadSpecificData)) { return 0; } // a
// gather the thread dispatch priorities for the compared critical sections
$dispPriorTableA = array(); // priority value => occurrences count
$dispPriorTableB = array(); // priority value => occurrences count
foreach (self::$bindStaticVariable[$a]->mastersThreadSpecificData as $thrdSpecificData)
@$dispPriorTableA[$thrdSpecificData['dispatchPriority']] += 1;
foreach (self::$bindStaticVariable[$b]->mastersThreadSpecificData as $thrdSpecificData)
@$dispPriorTableB[$thrdSpecificData['dispatchPriority']] += 1;
// both critical sections have threads
// make the tables to have the same amount of keys (rows)
foreach ($dispPriorTableA as $key => $value)
@$dispPriorTableB[$key] = $dispPriorTableB[$key]; // this is done on purpose
foreach ($dispPriorTableB as $key => $value)
@$dispPriorTableA[$key] = $dispPriorTableA[$key];
ksort($dispPriorTableA);
ksort($dispPriorTableB);
// compare the tables while taking into account the priority
// and the thread count that have it per critical section
foreach ($dispPriorTableA as $key => $value) {
if ($value < $dispPriorTableB[$key]) { return 1; } // b
else if ($value > $dispPriorTableB[$key]) { return -1; } // a
}
return 0; // a
} // }}}
/**
* Dispatcher responsible for the thread intercommunication and communication with their parent process.
* @param bool $useBlocking On true blocks the internal execution until communication data is available for the current dispatched thread otherwise it skips it.
* @return void
*/
public static function dispatch($useBlocking = false) { // {{{
$NULL = null;
// prevent any threads to run their own dispatchers
if ((self::$instancesCreatedEverAArr === null) || (count(self::$instancesCreatedEverAArr) == 0))
return;
// for checking SIGCHLD child signals informing that a particular "thread" was paused
$sigSet = array(SIGCHLD);
$sigInfo = array();
// begin the dispatching process
foreach (self::$instancesCreatedEverAArr as $instId => &$inst) { // loop through ALL active instances of GPhpCriticalSection
foreach ($inst->mastersThreadSpecificData as $threadId => &$specificDataAArr) { // loop though the threads per each instance in GPhpCriticalSection
// checking for child signals informing that a thread has exited or was paused
while (pcntl_sigtimedwait($sigSet, $sigInfo) == SIGCHLD) {
if ($sigInfo['code'] >= 0 && $sigInfo['code'] <= 3) { // child has exited
self::$threadsForRemovalAArr[$sigInfo['pid']] = $sigInfo['pid'];
} else if ($sigInfo['code'] == 5) { // stopped (paused) child
$specificDataAArr['dispatchPriority'] = 0; // make the dispatch priority lowest
} else if ($sigInfo['code'] == 6) { // resume stopped (paused) child
$specificDataAArr['dispatchPriority'] = 1; // increase little bit the priority since we expect interaction with the critical section
}
}
$inst->intercomInterlocutorPid = &$specificDataAArr['intercomInterlocutorPid'];
if (isset(self::$threadsForRemovalAArr[$inst->intercomInterlocutorPid])) {
unset($inst->mastersThreadSpecificData[$threadId]);
continue;
}
$inst->intercomRead = &$specificDataAArr['intercomRead'];
$inst->intercomWrite = &$specificDataAArr['intercomWrite'];
$inst->dispatchPriority = &$specificDataAArr['dispatchPriority'];
if (!$useBlocking && !$inst->intercomRead->isReceivingDataAvailable()) {
$inst->dispatchPriority = 0;
if ($inst->isIntercomBroken()) {
unset($inst->mastersThreadSpecificData[$threadId]); // remove the thread from the dispatching list as soon as we can
}
continue;
}
self::dataDispatch($inst, $threadId);
$mostPrioritizedThreadId = NULL;
if ($inst->dispatchPriority !== 2) {
foreach ($inst->mastersThreadSpecificData as $threadId2 => &$specificDataAArr2) {
if ($specificDataAArr2['dispatchPriority'] === 2) {
$mostPrioritizedThreadId = $threadId2;
}
}
} else {
$mostPrioritizedThreadId = $threadId;
}
if ($mostPrioritizedThreadId !== NULL && $mostPrioritizedThreadId !== $threadId) {
$inst->intercomInterlocutorPid = &$inst->mastersThreadSpecificData[$mostPrioritizedThreadId]['intercomInterlocutorPid'];
$inst->intercomRead = &$inst->mastersThreadSpecificData[$mostPrioritizedThreadId]['intercomRead'];
$inst->intercomWrite = &$inst->mastersThreadSpecificData[$mostPrioritizedThreadId]['intercomWrite'];
$inst->dispatchPriority = &$inst->mastersThreadSpecificData[$mostPrioritizedThreadId]['dispatchPriority'];
if (!$useBlocking && !$inst->intercomRead->isReceivingDataAvailable()) {
$inst->dispatchPriority = 0;
if ($inst->isIntercomBroken()) {
unset($inst->mastersThreadSpecificData[$mostPrioritizedThreadId]); // remove the thread from the dispatching list as soon as we can
}
continue;
}
self::dataDispatch($inst, $threadId);
}
}
// rearrange the threads in the current critical section
// instance using their new dispatch priority number
// if a lock has already occurred that thread will have the
// highest priority
$inst->bindVariable = &$inst;
uksort($inst->mastersThreadSpecificData, array($inst, 'sortByLockAndDispatchPriority'));
//uksort($inst->mastersThreadSpecificData,
// function ($a, $b) use ($inst) {
// if ($inst->mastersThreadSpecificData[$a]['intercomInterlocutorPid'] == $inst->ownerPid) return -1;
// if ($inst->mastersThreadSpecificData[$b]['intercomInterlocutorPid'] == $inst->ownerPid) return 1;
// return $inst->mastersThreadSpecificData[$a]['dispatchPriority'] < $inst->mastersThreadSpecificData[$b]['dispatchPriority'];
// }
//);
$inst->intercomInterlocutorPid = &$NULL;
$inst->intercomRead = &$NULL;
$inst->intercomWrite = &$NULL;
$inst->dispatchPriority = &$NULL;
}
// make sure that no terminated threads are left in the internal thread
// dispatching list that all instances of GPhpThreadCriticalSection have
foreach (self::$instancesCreatedEverAArr as $instId => &$inst) {
foreach ($inst->mastersThreadSpecificData as $threadId => &$specificDataAArr) {
$inst->intercomInterlocutorPid = &$specificDataAArr['intercomInterlocutorPid'];
if (isset(self::$threadsForRemovalAArr[$inst->intercomInterlocutorPid]))
unset($inst->mastersThreadSpecificData[$threadId]);
}
$inst->intercomInterlocutorPid = &$NULL;
}
self::$threadsForRemovalAArr = array();
// rearrange the active instances of GPhpThreadCriticalSection in the
// following priority order (the higher the number the bigger the priority):
// 2. the instance with the thread that has currently locked the critical section
// 1. instances with threads with the highest dispatch priority
// 0. instances with the most threads inside
self::$bindStaticVariable = &self::$instancesCreatedEverAArr;
uksort(self::$bindStaticVariable,
array('GPhpThreadCriticalSection', 'sortByLockDispatchPriorityAndMostThreadsInside'));
//$instCrtdEver = &self::$instancesCreatedEverAArr;
//uksort($instCrtdEver,
// function ($a, $b) use ($instCrtdEver) {
// // the locker thread is with highest priority
// if ($instCrtdEver[$a]->mastersThreadSpecificData['intercomInterlocutorPid'] == $instCrtdEver[$a]->ownerPid) return -1;
// if ($instCrtdEver[$b]->mastersThreadSpecificData['intercomInterlocutorPid'] == $instCrtdEver[$b]->ownerPid) return 1;
//
// // deal with the case of critical sections with no threads
// if (!empty($instCrtdEver[$a]->mastersThreadSpecificData) && empty($instCrtdEver[$b]->mastersThreadSpecificData)) { return -1; } // a
// else if (empty($instCrtdEver[$a]->mastersThreadSpecificData) && !empty($instCrtdEver[$b]->mastersThreadSpecificData)) { return 1; } // b
// else if (empty($instCrtdEver[$b]->mastersThreadSpecificData) && empty($instCrtdEver[$b]->mastersThreadSpecificData)) { return 0; } // a
//
// // gather the thread dispatch priorities for the compared critical sections
//
// $dispPriorTableA = array(); // priority value => occurrences count
// $dispPriorTableB = array(); // priority value => occurrences count
//
// foreach ($instCrtdEver[$a]->mastersThreadSpecificData as $thrdSpecificData)
// @$dispPriorTableA[$thrdSpecificData['dispatchPriority']] += 1;
//
// foreach ($instCrtdEver[$b]->mastersThreadSpecificData as $thrdSpecificData)
// @$dispPriorTableB[$thrdSpecificData['dispatchPriority']] += 1;
//
// // both critical sections have threads