Home  >  Article  >  Backend Development  >  How to implement multi-process in php

How to implement multi-process in php

藏色散人
藏色散人Original
2020-10-22 09:23:083215browse

php method to implement multi-process: first enable the pcntl extension; then use the array_chunk function to cut the specified array into an array of 500 elements; then perform parent process logic processing and child process processing; finally wait for the child process to execute Just end it.

How to implement multi-process in php

Recommended: "PHP Video Tutorial"

php multi-process implementation

When a process takes too long to execute, you need to use multiple processes to decompose the task and shorten the program execution time

pcntl is a multi-process extension of PHP, and pcntl is the abbreviation of process control

Let's briefly talk about how pcntl implements multi-process.

pcntl_fork — Spawn a fork (child process) at the current position of the current process. Annotation: fork creates a child process. Both the parent process and the child process continue to execute from the fork position. The difference is that during the execution of the parent process, the return value of fork is the child process number, while the child process gets 0.

Example:

$habit_class这个数组有5000条数据,所以先用array_chunk函数把该数组切割为每500个元素一个数组。
$habit_class = array_chunk($habit_class,500,true);
foreach($habit_class as $k2=>$v2){
$pid = pcntl_fork();
if ($pid == -1) {
die("could not fork");
} elseif ($pid) {
//这里是父进程逻辑处理,父进程会返回子进程的pid;
} else {// 子进程处理,子进程返回的pid未0;
foreach($v2 as $k=>$v){
    //进行具体业务处理
}
}
exit;// 一定要注意退出子进程,否则pcntl_fork() 会被子进程再fork,带来处理上的影响。
}
}
// 等待子进程执行结束
while (pcntl_waitpid(0, $status) != -1) {
$status = pcntl_wexitstatus($status);
//echo "Child $status completed\n";
}

The above is the detailed content of How to implement multi-process 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