Home  >  Article  >  Backend Development  >  PHP implements multi-process and multi-threading

PHP implements multi-process and multi-threading

不言
不言Original
2018-05-03 11:07:142719browse

This article mainly introduces the implementation of multi-process and multi-threading in PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

Instructions for newbies:


Orphan process: If a parent process exits and one or more of its child processes are still running, those child processes will become orphan processes. The orphan process will be adopted by the init process (process number is 1), and the init process will complete the status collection work for them.

# Zombie process: A process uses fork to create a child process. If the child process exits and the parent process does not call wait or waitpid to obtain the status information of the child process, Then the process descriptor of the child process is still saved in the system. This process is called a zombie process.

 Zombie process hazards:If the process does not call wait/waitpid, Then the retained information will not be released, and its process number will always be occupied. However, the process number that the system can use is limited. If a large number of zombie processes are generated, it will cause problems because there is no available process number. The system cannot generate new processes. This is the hazard of zombie processes and should be avoided. Any child process (except init) does not disappear immediately after exit(), but leaves a data structure called a zombie process (Zombie), waiting for the parent process to process.

The zombie process that has been generated, the solution: Kill the parent process, and the zombie process it generates will be Become orphan processes, these orphan processes will be taken over by the init process, and the init process will wait() these orphan processes and release the resources in the system process table they occupy.

## Solutions to zombie processes

(1) Through the signal mechanism

When the child process exits Send the SIGCHILD signal to the parent process, and the parent process handles the SIGCHILD signal. Call wait in the signal processing function to handle the zombie process.

  (2) fork twice

Section 8.6 of "Advanced Programming in Unix Environment" is very detailed. The principle is to turn the child process into an orphan process, so that its parent process becomes an init process, and the zombie process can be processed through the init process.


Comparison between multi-process and multi-thread

##Data sharing and synchronizationData sharing is complex and requires IPC; data is separated and synchronization is simple

1) Prioritized threads that need to be frequently created and destroyed

Please see the comparison above for the reason.

The most common application of this principle is the Web server. A connection creates a thread, and when it is disconnected, the thread is destroyed. If a process is used, the cost of creation and destruction is unbearable

2) Prioritize the use of threads that require a large amount of calculations

The so-called large amount of calculations, of course, consumes a lot of CPU and switches frequently. In this case, threads are the most appropriate.

The most common principles of this kind are image processing and algorithm processing.

3) Threads are used for strong correlation processing, and processes are used for weak correlation processing.

What are strong correlation and weak correlation? It is difficult to define in theory, but you can understand it with a simple example.

General Server needs to complete the following tasks: message sending and receiving, message processing. "Message sending and receiving" and "message processing" are weakly related tasks, and "message processing" may be further divided into "message decoding" and "business processing". These two tasks are relatively more closely related. Therefore, "message sending and receiving" and "message processing" can be designed in separate processes, and "message decoding" and "business processing" can be designed in separate threads.

Of course, this division method is not static and can also be adjusted according to the actual situation.

4) It may be extended to multi-machine distributed user processes and multi-core distributed user threads

Please see the comparison above for the reason.

5) When all requirements are met, use the method you are most familiar with and best at

As for "data sharing, synchronization", "programming, debugging", How to choose between the so-called "complexity and simplicity" in the dimensions of "reliability", I can only say: there is no clear choice method. But I can tell you a selection principle: If both multi-processing and multi-threading can meet the requirements, then choose the one you are most familiar with and best at.

What needs to be reminded is: Although I have given so many selection principles, actual applications are basically a combination of "process and thread". Don't really fall into an either/or. Misunderstanding.

Consumption of resources:

From the kernel's point of view, the purpose of the process is to serve as the basis for allocating system resources (CPU time, memory, etc.) unit. A thread is an execution stream of a process and the basic unit of CPU scheduling and dispatch. It is a basic unit that is smaller than a process and can run independently.

Threads, they use the same address space with each other and share most of the data. The space taken to start a thread is much less than the space taken to start a process. Moreover, the time required to switch between threads is also far. Much less than the time required to switch between processes. According to statistics, in general, the overhead of a process is about 30 times that of a thread. Of course, on specific systems, this data may be significantly different.

Communication method:

The only way to transfer data between processes is through communication, which is time-consuming and inconvenient. Most of the thread time data is shared (not shared within the thread function), which is fast and convenient. However, data synchronization requires locks. Pay special attention to static variables.

Thread's own advantages:

Improve application response; make multi-CPU systems more effective. The operating system will ensure that when the number of threads is not greater than the number of CPUs, different threads run on different CPUs;

Improve the program structure. A long and complex process can be divided into multiple threads and become several independent or semi-independent running parts. Such a program will be easier to understand and modify.

1. [Code] PHP implements multi-process parallel operation (can be used as a daemon)

/**
 * 入口函数
 * 将此文件保存为 ProcessOpera.php
 * 在terminal中运行 /usr/local/php/bin/php ProcessOpera.php & 
 * 查看进程 ps aux|grep php
 */
 
 
ProcessOpera("runCode", array(), 8);
 
/**
 * run Code
 */
function runCode($opt = array()) {
   //需要在守护进程中运行的代码
}
 
/**
 * $func为子进程执行具体事物的函数名称
 * $opt为$func的参数 数组形式
 * $pNum 为fork的子进程数量
 */
function ProcessOpera($func, $opts = array(), $pNum = 1) {
    while(true) {
        $pid = pcntl_fork();
        if($pid == -1) {
            exit("pid fork error");
        }   
        if($pid) {
            static $execute = 0;
            $execute++;
            if($execute >= $pNum) {
                pcntl_wait($status);
                $execute--;
            }   
        } else {
            while(true) {
                //somecode
                $func($opts);
                sleep(1);
            }   
            exit(0);
        }   
    }   
}

2. [Code] PHP implements multi-threaded operation

class My extends Thread {
    protected $name;
    public $runing;
    function __construct($name){
        $this->runing=1;
        $this->param=0;
        $this->name=$name;
    }
    public function run() {
        while($this->runing){
            if($this->param){
                $time=rand(1,5);
                echo 'I am thread '.$this->name.',pid: '.$this->getCreatorId().",param: {$this->param},need {$time}s\n"; 
                sleep($time);
                $this->param=0;
            }else{
                echo "Thread {$this->name} waiting...\n";
            }
            sleep(1);
        }
    }
}
$pool=array();
$pool[]=new My('a');
$pool[]=new My('b');
$pool[]=new My('c');
//开启所有线程
foreach ($pool as $w) {
    $w->start();
}
//派发任务
unset($w);
for($i=1;$i<10;$i++){
    $woker_content=$i;
    while(1){
        foreach($pool as $w){
            if(!$w->param){
                $w->param=$woker_content;
                echo "Thread {$w->name} empty,put param {$woker_content}.\n";
                break 2;
            }
        }
        sleep(1);    
    }
}


unset($w);
while(count($pool)){
    foreach ($pool as $k => $w) {
        if(!$w->param){
            $w->runing=false;
            unset($pool[$k]);
            echo "Thread {$w->name} end,exit!\n";
        }
    }
    sleep(1);
}


echo 'All thread end!';

Related recommendations:

Detailed explanation of five ways to implement scheduled tasks in PHP


Comparison dimension

Multiple processes

Multiple threads

Summary

Because process data is shared, data sharing is simple, but it is also for this reason that synchronization is complicated

Each has its own advantages

Memory, CPU

Occupies a lot of memory, complex switching, low CPU utilization

Occupies a small amount of memory , simple switching, high CPU utilization

Thread dominance

Creation, destruction, switching

Creation, destruction and switching are complex and slow

Creation, destruction and switching are simple and fast

Thread occupancy Excellent

Programming and debugging

Easy programming and easy debugging

Programming is complex, debugging is complex

Process Dominance

##Reliability

Processes will not affect each other

If one thread hangs up, the entire process will hang up

The process has the upper hand

Distributed

Suitable for multi-core and multi-machine distribution; if one machine is not enough, it is relatively simple to expand to multiple machines

Adapted to multi-core distribution

Process dominance

The above is the detailed content of PHP implements multi-process and multi-threading. 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