Home  >  Article  >  Backend Development  >  Multiple processes in PHP

Multiple processes in PHP

王林
王林Original
2023-05-23 08:39:322090browse

With the development of the Internet, more and more websites need to carry a large number of user access requests. When faced with high concurrency, a single-process server will quickly reach a bottleneck, causing users to be unable to access the website normally. Therefore, multi-process has become one of the effective solutions to solve high concurrency problems. This article will introduce the multi-process technology in PHP to improve the program's ability to handle concurrent requests while ensuring program quality.

1. Introduction to multi-process

In computer science, a process refers to an executing program instance. Each process has its own memory space and system resources. Multiprocessing refers to creating multiple processes in one program. Each process executes independently, has its own process number and process control block, and does not interfere with each other. Multi-process technology is widely used in server software, operating systems and other fields.

2. Multi-process in PHP

  1. Methods to implement multi-process

To implement multi-process in PHP, you can use pcntl extension or posix extension. Both extensions provide functions such as process creation, inter-process communication, signal handling, etc.

pcntl extension is PHP's process control function library, which provides many functions for creating, operating and managing processes. Using the pcntl function library to implement multiple processes can easily control the parent-child relationship, signal transmission, resource sharing, etc. of the process.

posix extension also provides process control, signal processing and other functions, which is a supplement to the pcntl extension. It also provides more system functions, such as file operations, system information query, etc.

  1. Create a child process

Create a child process in PHP by using the pcntl_fork() function. The return value of the fork() function is different, which can distinguish the parent process and the child process, thereby realizing the distinction between parent and child processes.

$pid = pcntl_fork();   // 创建子进程
if ($pid == -1) {
    die('fork failed');
} elseif ($pid == 0) { // 子进程
    // 子进程代码
} else {                // 父进程
    // 父进程代码
}

After the fork() function is called, the operating system will create a new child process. At this time, the main process can continue to execute and the child process will start executing after the fork() function. The pid of the child process is 0, and the pid of the parent process is the pid value of the child process. After creating a subprocess, we can perform some time-consuming operations in the subprocess, or perform some tasks in parallel, thereby improving the concurrency performance of the entire processing system.

  1. The exit status of the child process

After the child process completes execution, we need to obtain its exit status. In the pcntl_waitpid() function, the first parameter is the process number waiting for the child process to end, and the second parameter is the location where the child process exit status is stored. When the return value is positive, it means that the child process has exited, otherwise it means that it was interrupted by a signal while waiting.

$pid = pcntl_fork();
if ($pid == -1) {
    die('fork failed');
} elseif ($pid == 0) {
    // 子进程
    exit(0); // 子进程退出状态为0
} else {
    // 父进程
    pcntl_waitpid($pid, $status); // 等待子进程退出
    echo $status;   // 输出子进程退出状态
}

3. Practical Case

The following uses a simple practical case to illustrate how to use multi-process technology in PHP.

Implement a script to obtain the contents of multiple URLs, obtain the URL contents simultaneously by creating multiple sub-processes, and save their contents to the database after successful acquisition.

<?php
// 需要获取的URL列表
$urlList = [
    'https://www.baidu.com/',
    'https://www.qq.com/',
    'https://www.sina.com.cn/',
    'https://www.163.com/',
    'https://www.taobao.com/'
];

// 创建多个子进程并行获取URL内容
foreach ($urlList as $url) {
    $pid = pcntl_fork();
    if ($pid == -1) {
        die('fork failed');
    } elseif ($pid == 0) {
        // 子进程
        $content = file_get_contents($url); // 获取URL内容
        // 保存内容到数据库
        $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
        $stmt = $pdo->prepare("INSERT INTO url_content(url, content) VALUES(?, ?)");
        $stmt->execute([$url, $content]);
        exit(0);
    }
}

// 等待所有子进程执行完毕
while (pcntl_waitpid(0, $status) != -1) {
    // do nothing
}
echo 'All child processes have terminated' . PHP_EOL;

In the above code, we traverse $urllist through foreach and create multiple sub-processes to obtain URL content in parallel. After obtaining the URL content through the file_get_contents() function, we save the content to the database. In the parent process, wait for the child process to complete execution through the while and pcntl_waitpid() functions.

4. Notes

When using multi-process technology, you need to pay attention to the following points:

  1. The child process must exit before the parent process ends, otherwise it will Create a zombie process.
  2. The child process will only make a copy when the parent process is created. Content modified by the child process will not affect the parent process, and content modified by the parent process will not affect the child process.
  3. When the child process is created, all variables and file descriptors of the parent process will be copied, but the streams opened by the parent process will not be copied.
  4. When using multi-process technology, you need to consider the system resource usage to avoid excessive consumption of system resources.

5. Summary

The application of multi-process technology in PHP can effectively improve the program's ability to handle concurrent requests. Through multi-process technology, multiple tasks can be processed in parallel and the response speed and concurrency of the system can be improved. On the premise of ensuring program quality, multi-process technology provides us with an efficient and simple solution.

The above is the detailed content of 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