search
HomeBackend DevelopmentPHP TutorialTwo 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.

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 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');
?>

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
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.