Home Backend Development PHP7 A preliminary study on multiple processes in PHP7

A preliminary study on multiple processes in PHP7

Apr 04, 2019 pm 01:52 PM
php7 multi-Progress

Preparation

We all know that PHP is executed in a single process. PHP's handling of multi-concurrency mainly relies on the multi-process of the server or PHP-FPM and the reuse of their processes, but PHP Implementing multiple processes is also of great significance, especially when processing large amounts of data in background Cli mode or running background DEMON daemon processes. Needless to say, the advantages of multiple processes.

PHP's multi-threading has also been mentioned, but the problem of multi-thread resource sharing and allocation within the process is difficult to solve. PHP also has multi-threading extension pthreads , but it is said to be unstable and requires the environment to be thread-safe, so it is not used much.

In the past, a great master in the PHP group once guided that if you want to advance in background PHP, you must avoid multi-process. It just so happens that the daemon process in the company also uses PHP's multi-process, combined with Gu Ge's various After reading the information and manuals, I finally understood multi-processing and wrote a small demo (implemented on a Linux system). I will summarize it in this article. If there are any mistakes or omissions, thank you for mentioning them.

To implement PHP multi-process, we need two extensions pcntl and posix. The installation method will not be described here.

In php we use pcntl_fork() to create multiple processes (in C language programming of *NIX systems, existing processes generate new processes by calling the fork function). The new process after the fork becomes the child process, the original process becomes the parent process, and the child process has a copy of the parent process. Note here:

• The child process shares the program text segment with the parent process

• The child process has a copy of the parent process's data space and heap and stack. Note that it is a copy, not a share

• The parent process and the child process will continue to execute the program code after the fork

• After the fork, whether the parent process or the child process executes first cannot be confirmed, and it depends on the system scheduling (depends on belief)

It is said here that the child process has a copy of the parent process's data space, heap, and stack. In fact, in most implementations, it is not a true complete copy. More importantly, COW (Copy On Write) technology is used to save storage space. To put it simply, if neither the parent process nor the child process modifies these data, heap, and stack, then the parent process and the child process temporarily share the same data, heap, and stack. Only when the parent process or child process attempts to modify the data, heap, and stack will a copy operation occur. This is called copy-on-write.

After calling pcntl_fork(), this function will return two values. Returns the process ID of the child process in the parent process, and returns the number 0 inside the child process itself. Since multiple processes cannot run properly in the apache or fpm environment, you must execute the code in the php cli environment.

Create sub-process

Creating a PHP sub-process is the beginning of multiple processes, we need pcntl_fork() function;

Detailed explanation of fork function

pcntl_fork() — Generate a branch (child process) at the current position of the current process. After this function creates a new child process, the child process will inherit the current context of the parent process and continue to execute downwards from the pcntl_fork() function like the parent process, except that the pcntl_fork is obtained () The return value is different, we can distinguish the parent process and the child process by judging the return value, and allocate the parent process and the child process to do different logical processing.

When the pcntl_fork() function is successfully executed, it will return the process id (pid) of the child process in the parent process. Because the pid of the system's initial process init process is 1, the pid of the subsequent processes will be greater than this process, so We can confirm that the current process is the parent process by judging that the return value of pcntl_fork() is greater than 1; in the child process, the return value of this function will be a fixed value of 0. We can also judge that the return value of pcntl_fork() is 0. To determine the child process; when the pcntl_fork() function fails to execute, it will return -1 in the parent process, and of course no child process will be generated.

fork process instance

fork child process

$ppid = posix_getpid();
$pid = pcntl_fork();
if ($pid == -1) {
    throw new Exception('fork child process fail');
} elseif ($pid > 0) {
    cli_set_process_title("我是父 process,pid is : {$ppid}.");
    sleep(30);
} else {
    $cpid = posix_getpid();
    cli_set_process_title("我是 {$ppid} 子的 process,我的 process pid is : {$cpid}.");
    sleep(30);
}
Copy after login

Description:

posix_getpid(): Return the current process id

cli_set_process_title('Process Name'): Give the current process a loud name.

Running this example, we can see the current two PHP processes.

www@iZ2zec3dge6rwz2uw4tveuZ:~/test$ ps aux|grep -v grep |grep 我
www      18026  0.5  1.2 204068 25772 pts/0    S+   14:08   0:00 我是父 process,pid is : 18026.
www      18027  0.0  0.3 204068  6640 pts/0    S+   14:08   0:00 我 18026 子的 process,我的 process pid is : 18027. 
Copy after login

The first section of code, after the program starts from pcntl_fork(), the parent process and the child process will continue to execute the code:

$pid = pcntl_fork();
if( $pid > 0 ){
  echo "我是父亲".PHP_EOL;
} else if( 0 == $pid ) {
  echo "我是儿子".PHP_EOL;
} else {
  echo "fork失败".PHP_EOL;
} 
Copy after login

The result:

www@iZ2zec3dge6rwz2uw4tveuZ:~/test$ php 123.php
我是父亲
我是儿子
Copy after login

The second section Code to illustrate that the child process has a copy of the data of the parent process, rather than sharing:

// 初始化一个 number变量 数值为1
$number = 1;
$pid = pcntl_fork();
if ($pid > 0) {
    $number += 1;
    echo "我是父亲,number+1 : { $number }" . PHP_EOL;
} else if (0 == $pid) {
    $number += 2;
    echo "我是儿子,number+2 : { $number }" . PHP_EOL;
} else {
    echo "fork失败" . PHP_EOL;
}
Copy after login

Result

www@iZ2zec3dge6rwz2uw4tveuZ:~/test$ php 1234.php
我是父亲,number+1 : { 2 }
我是儿子,number+2 : { 3 }
Copy after login

The above is the detailed content of A preliminary study on multiple processes in PHP7. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Application method of shared memory between multiple processes in Golang function Application method of shared memory between multiple processes in Golang function May 17, 2023 pm 12:52 PM

As a highly concurrent programming language, Golang's built-in coroutine mechanism and multi-threaded operations enable lightweight multi-tasking. However, in a multi-process processing scenario, communication and shared memory between different processes have become key issues in program development. This article will introduce the application method of realizing shared memory between multiple processes in Golang. 1. How to implement multi-process in Golang In Golang, multi-process concurrent processing can be implemented in a variety of ways, including fork, os.Process,

How to install mongo extension in php7.0 How to install mongo extension in php7.0 Nov 21, 2022 am 10:25 AM

How to install the mongo extension in php7.0: 1. Create the mongodb user group and user; 2. Download the mongodb source code package and place the source code package in the "/usr/local/src/" directory; 3. Enter "src/" directory; 4. Unzip the source code package; 5. Create the mongodb file directory; 6. Copy the files to the "mongodb/" directory; 7. Create the mongodb configuration file and modify the configuration.

What should I do if the plug-in is installed in php7.0 but it still shows that it is not installed? What should I do if the plug-in is installed in php7.0 but it still shows that it is not installed? Apr 02, 2024 pm 07:39 PM

To resolve the plugin not showing installed issue in PHP 7.0: Check the plugin configuration and enable the plugin. Restart PHP to apply configuration changes. Check the plugin file permissions to make sure they are correct. Install missing dependencies to ensure the plugin functions properly. If all other steps fail, rebuild PHP. Other possible causes include incompatible plugin versions, loading the wrong version, or PHP configuration issues.

How to solve the problem when php7 detects that the tcp port is not working How to solve the problem when php7 detects that the tcp port is not working Mar 22, 2023 am 09:30 AM

In php5, we can use the fsockopen() function to detect the TCP port. This function can be used to open a network connection and perform some network communication. But in php7, the fsockopen() function may encounter some problems, such as being unable to open the port, unable to connect to the server, etc. In order to solve this problem, we can use the socket_create() function and socket_connect() function to detect the TCP port.

Let's talk about multi-process and multi-threading in Node.js Let's talk about multi-process and multi-threading in Node.js Jul 25, 2022 pm 07:45 PM

Everyone knows that Node.js is single-threaded, but they don’t know that it also provides a multi-thread module to speed up the processing of some special tasks. This article will lead you to understand the multi-threading of Node.js, hoping to learn more about it. Everyone helps!

Is golang multi-process? Is golang multi-process? Jul 07, 2023 am 10:18 AM

Golang is a multi-process, and its thread model is the MPG model. Overall, Go processes and kernel threads correspond to many-to-many, so first of all, they must be multi-threaded. Golang has some so-called M ratio N model. N go routines can be created under M threads. Generally speaking, N is much larger than M. It is essentially a multi-threaded model. However, the scheduling of coroutines is determined by the runtime of Go. It is emphasized that developers should Use channels for synchronization between coroutines.

PHP Server Environment FAQ Guide: Quickly Solve Common Problems PHP Server Environment FAQ Guide: Quickly Solve Common Problems Apr 09, 2024 pm 01:33 PM

Common solutions for PHP server environments include ensuring that the correct PHP version is installed and that relevant files have been copied to the module directory. Disable SELinux temporarily or permanently. Check and configure PHP.ini to ensure that necessary extensions have been added and set up correctly. Start or restart the PHP-FPM service. Check the DNS settings for resolution issues.

How to install and deploy php7.0 How to install and deploy php7.0 Nov 30, 2022 am 09:56 AM

How to install and deploy php7.0: 1. Go to the PHP official website to download the installation version corresponding to the local system; 2. Extract the downloaded zip file to the specified directory; 3. Open the command line window and go to the "E:\php7" directory Just run the "php -v" command.

See all articles