PHP pcntl Multi-process usages _php tips

Source: Internet
Author: User

This article is an example of PHP's PCNTL multi-process usage. Share to everyone for your reference. The specific analysis is as follows:

PHP uses the PCNTL series functions to do multiple processes to handle a transaction. For example, I need to get 80w data from the database, and then do a series of subsequent processing, this time, with a single process? You can wait until next year today. So you should use the PCNTL function.

Let's say I want to start 20 processes, divide the 1-80w data into 20 parts, and the main process waits for all the child processes to end before exiting:

$max = 800000;
$workers =;
$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 out, will return a PID value, this PID in the child process see is 0, in the parent process is a child process PID (>0), if the PID 1 indicates that fork error.

Using a $pids array allows the main process to wait for all processes to end.

I hope this article will help you with your PHP program design.

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.