This article mainly introduces the usage of pcntl multi-process in PHP, and analyzes the usage skills of pcntl to operate multi-process, which is of great practical value, you can refer to the following example to describe the use of pcntl multi-process in PHP. Share it with you for your reference. The specific analysis is as follows:
PHP uses functions of the PCNTL series to process a transaction in multiple processes. For example, if I need to retrieve million pieces of data from the database and perform a series of subsequent processing, how can I use a single process? You can wait until next year. So we should use the pcntl function.
Suppose I want to start 20 processes and divide the data from 1 to 80 W into 20 parts. The main process will exit after all the sub-processes are completed:
$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, a pid value will be returned. this pid is 0 in the sub-process, and the pid in the parent process is the sub-process pid (> 0 ), if the pid is-1, the fork has an error.
With a $ pids array, the main process can be completed after all processes are completed.
I hope this article will help you with php programming.
For more articles about examples of pcntl multi-process usage in PHP, refer to the Chinese PHP website!