Two methods to implement multi-threading in PHP_PHP tutorial
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
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.
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
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
$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
echo "$i -> " . time() . " $str n";
exit();
// Subprocess process code segment_End
}
}
if ($bWaitFlag)
{
for($i = 0; $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');
?>

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool