Table of Contents
1. [Code] PHP implements multi-process parallel operation (can be used as a daemon) " >1. [Code] PHP implements multi-process parallel operation (can be used as a daemon)
2. [Code] PHP implements multi-threaded operation
Home Backend Development PHP Tutorial PHP implements multi-process and multi-threading

PHP implements multi-process and multi-threading

May 03, 2018 am 11:07 AM
php thread process

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)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

/**

 * 入口函数

 * 将此文件保存为 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);

        }  

    }  

}

Copy after login

2. [Code] PHP implements multi-threaded operation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

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 &#39;All thread end!&#39;;

Copy after login

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 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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1234
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles