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

WBOY
Release: 2016-07-13 09:44:14
Original
800 people have browsed it

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...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template