Table of Contents
Two methods to implement multi-threading in PHP
Home Backend Development PHP Tutorial Two methods to implement multi-threading in PHP_PHP tutorial

Two methods to implement multi-threading in PHP_PHP tutorial

Jul 13, 2016 am 09:44 AM
php indivual accomplish method of Simple thread

Two methods to implement multi-threading in PHP

Methods to implement multi-threading in PHP shell

Write a simple php code first. In order to make the script execution time longer and see the effect more easily, sleep for a while, haha! Let’s take a look at the code of test.php first: ls

PHP code:

for ($i=0;$i<10;$i ) {
echo $i;
sleep(10);
}
?>

Look at the code of the shell script, it is very simple

#!/bin/bash
for i in 1 2 3 4 5 6 7 8 9 10
do
/usr/bin/php -q /var/www/html/test.php &
done

Did you notice that there is an & symbol in the line that requests the PHP code? This is the key. Without it, multi-threading cannot be performed. & means that the service is pushed to the background for execution. Therefore, in each loop of the shell There is no need to wait for all the PHP code to be executed before requesting the next file. Instead, it is done at the same time, thus achieving multi-threading. Run the shell below to see the effect. Here you will see 10 test.php processes and then run. Then use the Linux timer to request this shell regularly, which is very useful when processing some tasks that require multi-threading, such as batch downloading!

Using WEB server to implement multi-threading in php

Suppose we are running the file a.php now. But I request the WEB server to run another b.php in the program, then the two files will be executed at the same time. (PS: After a link request is sent , the WEB server will execute it, regardless of whether the client has exited)

Sometimes, what we want to run is not another file, but a part of the code in this file. What should we do?
In fact, parameters are used to control which program a.php runs.

Look at an example below:

//a.php,b.php

PHP code:-------------------------------------------------- ----------------------------------

Function runThread()
{
$fp = fsockopen('localhost', 80, $errno, $errmsg);
                                                                                                                                                                                                                                                                                                     //If you don’t understand, please see the definition in RFC
                                                            fclose($fp);
}

Function a()
{
          $fp = fopen('result_a.log', 'w');
              fputs($fp, 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn");
                                                           fclose($fp);                                                              }

Function b()
{
          $fp = fopen('result_b.log', 'w');
              fputs($fp, 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn");
                                                           fclose($fp);                                                            }

If(!isset($_GET['act'])) $_GET['act'] = 'a';
 
If($_GET['act'] == 'a')
{
        runThread();
a();
}
​ else if($_GET['act'] == 'b') b();
?>
-------------------------------------------------- ----------------------------------


Open result_a.log and result_b.log and compare the access times of the two files. You will find that these two are indeed running in different threads. Some times are exactly the same.

The above is just a simple example, you can improve it into other forms.

Now that multi-threading is available in PHP, a problem arises, which is synchronization. We know that PHP itself does not support multi-threading. So there is no method like synchronize in Java. So what should we do? Doing it.

1. Try not to access the same resource to avoid conflicts. But you can operate the database at the same time. Because the database supports concurrent operations, do not write data to the same file in multi-threaded PHP. If necessary If you want to write, use other methods for synchronization. For example, call flock to lock the file, etc. Or create a temporary file and wait for the disappearance of the file in another thread while(file_exits('xxx')); This is equivalent to When this temporary file exists, it means that the thread is actually operating

If there is no such file, it means that other threads have released it.

2. Try not to read data from the socket that runThread takes after executing fputs. Because to achieve multi-threading, it is necessary to use non-blocking mode. That is, return immediately when functions like fgets are used. So read and write data Problems will arise. If blocking mode is used, the program is not multi-threaded. It has to wait for the return of the above before executing the following program. So if data needs to be exchanged, it can be completed using external files or data. If you really want it, just Use socket_set_nonblock($fp) to implement.


Having said so much, does this have any practical significance? When is it necessary to use this method?
The answer is yes. As we all know, in an application that constantly reads network resources, the speed of the network is the bottleneck. If you adopt this method, you can read different pages with multiple threads at the same time.

I made a program that can search for information from shopping mall websites such as 8848 and soaso. There is also a program that reads business information and company directories from the Alibaba website and also uses this technology. Because both programs have to continuously connect to their servers to read information and save it to the database. Utilizing this technology eliminates the bottleneck of waiting for a response.


Three ways to simulate multi-threading in PHP

The PHP language itself does not support multi-threading. I summarized the methods on the Internet for simulating multi-threading in PHP. Generally speaking, they all make use of the multi-threading capabilities of PHP’s good partners. PHP is good Partners refer to LINUX and APACHE, LAMP.

In addition, since it is simulated, it is not true multi-threading. In fact, it is just multi-process. Process and thread are two different concepts. Well, the following methods are all found from the Internet.

1. Using LINUX operating system

for ($i=0;$i<10;$i ) {
echo $i;
sleep(5);
}
?>

Save the above into test.php, and then write a SHELL code

#!/bin/bash
for i in 1 2 3 4 5 6 7 8 9 10
do
php -q test.php &
done

2. Use fork child process (in fact, it also uses the LINUX operating system)

declare(ticks=1);
$bWaitFlag = FALSE; /// Whether to wait for the process to end
$intNum = 10; /// Total number of processes
$pids = array(); /// Process PID array
echo ("Startn");
for($i = 0; $i < $intNum; $i ) {
$pids[$i] = pcntl_fork();/// Generate a child process, and start the test run code from the current line, and do not inherit the data information of the parent process
if(!$pids[$i]) {
// Subprocess process code segment_Start
$str="";
sleep(5 $i);
for ($j=0;$j<$i;$j ) {$str.="*";}
echo "$i -> " . time() . " $str n";
exit();
// Subprocess process code segment_End
}
}
if ($bWaitFlag)
{
for($i = 0; $i < $intNum; $i ) {
pcntl_waitpid($pids[$i], $status, WUNTRACED);
echo "wait $i -> " . time() . "n";
}
}
echo ("Endn");
?>

3. Using WEB SERVER, PHP does not support multi-threading, but APACHE does, haha.

Suppose we are running the document a.php. But I also request the WEB server to run another b.php in the program

Then the two documents will be executed at the same time. (The code is the same as above)

Of course, you can also leave the parts that require multi-threading to JAVA and then call them in PHP, haha.

system('java multiThread.java');
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1049987.htmlTechArticleTwo methods to implement multi-threading in PHP Methods to implement multi-threading in PHP shell First write a simple php code, here In order to make the script execution time longer and see the effect more easily, sleep for a while, haha! First...
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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

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

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

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.

See all articles