Two ways to implement multithreading in PHP

Source: Internet
Author: User
Tags php language php code sleep advantage

Php+shell Method of implementing multithreading

First write a simple PHP code, here in order to allow the script to perform longer, easy to see the effect of sleep, hehe! First look at the test.php code: LS

PHP Code:

<?php
For ($i =0 $i <10; $i + +) {
echo $i;
Sleep (10);
}
?>

Look at the code for the shell script, very simple

#!/bin/bash
For I in 1 2 3 4 5 6 7 8 9 10
Todo
/usr/bin/php-q/var/www/html/test.php &
Done

Notice that there is a & symbol on the line requesting PHP code, this is the key, without words is not to do multithreading,& Express service push to the background execution, therefore, in the shell of each loop without waiting for PHP code all executed in the request next file, but at the same time , so that the implementation of multithreading, below the shell to look at the effect, here you will see 10 test.php process and then run, and then use the Linux timer, timed request this shell, in the processing of a number of tasks that require multithreading, for example, the bulk of the download, very easy to use!

Using Web Server in PHP to implement multithreading

Let's say we're running a.php this file. But I also request the Web server to run another b.php in the program, so the two files will be executed concurrently. (PS: After a link request is sent, the Web server executes it, regardless of whether the client has exited)

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

Let's look at an example:

a.php,b.php

PHP Code:--------------------------------------------------------------------------------

&lt;?php


function Runthread ()


    {


$fp = fsockopen (' localhost ', $errno, $errmsg);


        


fputs ($fp, "get/b.php?act=brnrn"); The second parameter here is the request header specified in the HTTP protocol


//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 ();


?&gt;


--------------------------------------------------------------------------------


Open Result_a.log and Result_b.log to compare the time of access in two files. As you can see, these two are actually running on different threads. Some time is exactly the same.

The above is just a simple example that can be improved into other forms.


Since PHP can also be more than a thread, then the problem has come, that is the problem of synchronization. We know that PHP itself does not support multithreading. So there's nothing like synchronize in Java. So how do we do that?

1. Try not to access the same resources. To avoid conflicts. However, you can operate as a database at the same time. Because the database is a concurrency-enabled operation. So do not write data to the same file in multithreaded PHP. If you have to write, use a different method to sync. such as calling flock to lock the file. or create a temporary file and wait for the file to disappear while in another thread (file_exits (' xxx ')); This is equal to the presence of this temporary file, which means that the thread is actually operating

If this file is not there, other threads have released this.

2. Try not to read the data from the runthread after the execution of the socket fputs. Because to implement multithreading, you need to use non-blocking mode. That is, it returns immediately when a function like fgets ... So reading and writing data can be problematic. If you use blocking mode, the program is not multi-threaded. He will wait until the above return to execute the following program. So if you need to exchange data, you end up using outside files or data. If you really want it, use Socket_set_nonblock ($FP) to achieve it.


Having said so much, does this have any practical significance? When does this need to be used in this way?
The answer is yes. You know. In a continuous reading of network resources, the speed of the network is the bottleneck. If you use this form, you can read different pages simultaneously with multiple threads.

I do a can from 8848, Soaso these mall website search information program. There is also a program that reads business information and company catalogs from Alibaba's website. Because both programs are constantly linking their servers to read the information and save it to the database. The use of this technique eliminates the bottleneck in waiting for a response.


Three ways to implement multithreading in PHP simulation

The PHP language itself does not support multithreading. summed up the web about the PHP simulation of multithreading methods, in general, are taking advantage of the good partners in PHP itself has the ability to multithreading. PHP's good partners are Linux and Apache, lamp.

In addition, since it is analog, it is not really multithreading. Actually, it's just a lot of progress. Processes and threads are two different concepts. Well, the following methods are all found on the Internet.

1. Use Linux operating system

<?php
For ($i =0 $i <10; $i + +) {
echo $i;
Sleep (5);
}
?>

Save it as a test.php, then write a shell code

#!/bin/bash
For I in 1 2 3 4 5 6 7 8 9 10
Todo
Php-q test.php &
Done

2. Take advantage of the fork process (in fact, using the Linux operating system as well)

<?php
Declare (Ticks=1);
$bWaitFlag = FALSE; Whether to wait for the process to end
$intNum = 10; Total Processes
$pids = Array (); Process PID Arrays
Echo ("Startn");
for ($i = 0; $i < $intNum; $i + +) {
$pids [$i] = Pcntl_fork ();///produces the subprocess and runs the code from under the current line and does not inherit the data information from the parent process
if (! $pids [$i]) {
Child process Process Code snippet _start
$str = "";
Sleep (5+ $i);
For ($j =0 $j < $i; $j + +) {$str. = "*";}
echo "$i->". Time (). "$str n";
Exit ();
Child process Process Code snippet _end
}
}
if ($bWaitFlag)
{
for ($i = 0; $i < $intNum; $i + +) {
Pcntl_waitpid ($pids [$i], $status, wuntraced);
echo "Wait $i->". Time (). "N";
}
}
Echo ("Endn");
?>

3. The use of Web SERVER, PHP does not support multithreading, Apache but support, hehe.

Let's say we're running a.php this document. But I also requested the Web server to run another b.php in the program

Then the two documents will be executed concurrently. (Code ditto)

Of course, you can also need to handle a number of threads to Java to deal with, and then call in PHP, haha.

<?php
System (' Java Multithread.java ');
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.