Example of PHP pcntl multi-process usage

Source: Internet
Author: User
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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.