Home > Article > Backend Development > PHP pcntl multi-process usage example
The example in this article describes the usage of PHP's pcntl multi-process. Share it with everyone for your reference. The specific analysis is as follows:
PHP can also process a transaction with multiple processes using the PCNTL series of functions. For example, I need to obtain 800,000 pieces of data from the database and then perform a series of subsequent processing. At this time, should I use a single process? You can wait until today next year. So you should use the pcntl function.
Suppose I want to start 20 processes and divide 1-80w of data into 20 parts. The main process waits for all sub-processes to finish before exiting:
$max = 800000; $workers = 20; $pids = array(); for($i = 0; $i < $workers; $i++){ $pids[$i] = pcntl_fork(); switch ($pids[$i]) { case -1: echo "fork error : {$i} \r\n"; exit; case 0: $param = array( 'lastid' => $max / $workers * $i, 'maxid' => $max / $workers * ($i+1), ); $this->executeWorker($input, $output, $param); exit; default: break; } } foreach ($pids as $i => $pid) { if($pid) { pcntl_waitpid($pid, $status); } }
Here when pcntl_fork comes out, it will return A pid value. This pid is 0 when viewed in the child process, and is the pid of the child process (>0) when viewed in the parent process. If the pid is -1, it means that a fork error occurred.
Using a $pids array allows the main process to wait for all processes to complete before ending it
I hope this article will be helpful to everyone's PHP programming design.
For more articles related to PHP’s pcntl multi-process usage examples, please pay attention to the PHP Chinese website!