Linux implementation of PHP multi process method sharing

  • 2020-05-19 04:18:45
  • OfStack

PHP multiprocess: Process Control Functions using PHP (PCNTL/ thread control function)
Function reference: http: / / www php. net manual/zh/ref pcntl. php
Unix Like OS only, Windows is not available.
To compile php, you need to add the hang enable-pcntl, and it is recommended to run only in CLI mode, not in the WEB server environment.

The following is a simple test code to implement PHP multi-process:
 
<?php 
declare(ticks=1); 
$bWaitFlag = FALSE; ///  Whether to wait for the process to end  
$intNum = 10; ///  The total number of processes  
$pids = array(); ///  process PID An array of  

echo ("Start\n"); 

for($i = 0; $i < $intNum; $i++) { 

$pids[$i] = pcntl_fork();///  Generates a child process and starts a trial run from under the current line, without inheriting data information from the parent process  

if(!$pids[$i]) { 
//  Child process process code segment _Start 
$str=""; 
sleep(5+$i); 
for ($j=0;$j<$i;$j++) {$str.="*";} 
echo "$i -> " . time() . " $str \n"; 
exit(); 
//  Child process process code segment _End 
} 

} 
if ($bWaitFlag) 
{ 
for($i = 0; $i < $intNum; $i++) { 
pcntl_waitpid($pids[$i], $status, WUNTRACED); 
echo "wait $i -> " . time() . "\n"; 
} 
} 
echo ("End\n"); 
?> 

Related articles: