Home  >  Article  >  Backend Development  >  How to use pcntl function to operate multiple processes in PHP

How to use pcntl function to operate multiple processes in PHP

墨辰丷
墨辰丷Original
2018-06-12 13:49:191312browse

This article mainly introduces the usage of PHP's pcntl multi-process. The example analyzes the usage skills of pcntl operating multi-process. It is of great practical value. Friends in need can refer to it.

The example of this article describes the use of PHP pcntl multi-process usage. The specific analysis is as follows:

PHP can also handle 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 the 1-80w data into 20 parts. The main process waits for all child 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(
        &#39;lastid&#39; => $max / $workers * $i,
        &#39;maxid&#39; => $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 In the future, a pid value will be returned. This pid is 0 in the child process, and is the pid of the child process (>0) in the parent process. If the pid is -1, it means that the fork went wrong.

Using a $pids array allows the main process to wait for all processes to complete before ending it

Summary: The above is the entire content of this article, I hope it can help Everyone’s learning helps.

Related recommendations:

The database in PHP implements more secure permanent login and remember me functions

Use generated in PHP Methods for encrypting and decrypting public keys and private keys

php records user names and passwords based on cookies

The above is the detailed content of How to use pcntl function to operate multiple processes in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn