Joke Collection Website - Blessing messages - php multi-threading tutorial?
php multi-threading tutorial?
PHP+shell method to implement multi-threading
First write a simple PHP code. In order to make the script execution time longer and see the effect more conveniently, sleep for a while, haha! Read it first Download the code of test.php: 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
foriin12345678910
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 In each loop of the shell, you do not have to wait for all the PHP code to be executed before requesting the next file. Instead, you do it at the same time, thus achieving multi-threading. Run the shell below to see the effect. Here you will see 10 tests. The .php process is run again, and then the Linux timer is used to request this shell regularly. It is very useful when processing some tasks that require multi-threading, such as batch downloading!
Use WEB server in PHP to implement Multi-threading
Suppose we are running the file a.php. But in the program, I request the WEB server to run another b.php, 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, we can use parameters to control which program a.php runs.
Let’s look at an example:
//a. php,b.php
PHP code:---------------------------------- ---------------------------------------------
< p>functionrunThread(){
$fp=fsockopen('localhost',80,$errno,$errmsg);
fputs($fp, \"GET/b.php?act=b\");//The second parameter here is p>
fclose($fp);
}
functiona()
{
$fp=fopen('result_a.log','w');
fputs($fp, 'Setin'.Date('h:i:s',time()).(double)microtime().\"\");
fclose($fp);
< p>}functionb()
{
$fp=fopen('result_b.log','w');
fputs($fp,'Setin'.Date('h:i:s',time()).(double)microtime().\"\");
fclose($fp) ;
}
if(!isset($_GET['act']))$_GET['act']='a';
if ($_GET['act']=='a')
{
runThread();
a();
}
elseif($_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.
Since PHP can also have multi-threading, the problem has also arisen. That is the problem of 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?
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 you must write, use other methods Synchronize. For example, call flock to lock the file, etc. Or create a temporary file and wait for the file to disappear in another thread while(file_exits('xxx')); This means that when the temporary file exists, it means that in fact The thread is operating
If there is no such file, it means that other threads have released it.
2. Try not to read data from this socket after runThread executes fputs. Because To achieve multi-threading, you need to use non-blocking mode. That is, return immediately when a function like fgets is used. So there will be problems when reading and writing data. If blocking mode is used, the program is not multi-threaded. He has to wait. The following program will be executed only after the above return. Therefore, if you need to exchange data, you can finally use external files or data to complete it. If you really want to, use socket_set_nonblock($fp) to achieve it.
Having said so much, it is actually 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 continuously reads network resources, the speed of the network It is a 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 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 online methods of PHP simulating multi-threading. In general, They all take advantage of the multi-threading capabilities of PHP's good partners. PHP's good partners refer to LINUX and APACHE, and LAMP.
In addition, since it is simulated, it is not real. 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. Use the LINUX operating system
for($i=0;$i<10;$i++){
echo$i;
sleep(5);
} >< /p>
Save the above as test.php, and then write a SHELL code
#!/bin/bash
foriin12345678910
do
php-qtest.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++){< /p>
$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().\"$strn\";
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.Use WEBSERVER, PHP does not support multi-threading, but APACHE does support it, haha.
Suppose we are running the document a.php. But I also request the WEB server to run another b.php in the program< /p>
Then the two documents will be executed at the same time. (The code is the same as above)
Of course, you can also hand over the parts that require multi-thread processing to JAVA, and then use it in PHP Call, haha.
system('javamultiThread.java'); >
Extended information: PHP, the "hypertext preprocessor", is a general open source scripting language. PHP is a scripting language executed on the server side. It is similar to C language and is a commonly used website programming language. PHP's unique syntax mixes C, Java, Perl, and PHP's own syntax. It is conducive to learning and widely used. It is mainly suitable for the field of web development.
- Related articles
- A greeting to a friend when the weather is cold?
- How to delete spam messages
- How to open this card with a U shield? Can I transfer money without a U shield?
- May 1 safety slogan
- What happened when I suddenly received the verification code of Shanghai remittance data?
- How to coax your girlfriend into a headache?
- What is the inspection code of the international freight forwarder?
- A message of blessing to parents during Mid-Autumn Festival.
- Building materials sales skills, how to sell building materials, building materials sales?
- The plot of black flowers in the sea of stealing pens and sand