PHP itself does not have multithreading, it can be implemented with the help of extension. But the curl_multi* function realizes the function of multithreading accessing the data of the website.
The steps are summarized as follows:
First step: Call Curl_multi_init
Step two: Loop call Curl_multi_add_handle
In this step, it should be noted that the second parameter of Curl_multi_add_handle is a curl_init handle.
Step three: Keep calling Curl_multi_exec
Step Fourth: Loop call curl_multi_getcontent to get results as needed
Step Fifth: Call Curl_multi_remove_handle and call curl_close for each word handle
Step Sixth: Call Curl_multi_close
| The code is as follows |
Copy Code |
|
<?php
$t =gettime ();
$total = 10;
for ($i =0; $i < $total; $i + +) {
$url _arr[] = "Http://www.111cn.net/test";
}
$MH = Curl_multi_init ();
foreach ($url _arr as $i => $url) {
$conn [$i] = Curl_init ($url);
curl_setopt ($conn [$i],curlopt_returntransfer,1); Set return page output content
Curl_multi_add_handle ($MH, $conn [$i]); adding threads
}
#----------------Thread Execution----------------
do {
$MRC = Curl_multi_exec ($MH, $active);
}while ($MRC = = Curlm_call_multi_perform);
while ($active and $MRC = = CURLM_OK) {
if (Curl_multi_select ($MH)!=-1) {
do {
$MRC = Curl_multi_exec ($MH, $active);
while ($MRC = = Curlm_call_multi_perform);
}
}
foreach ($url _arr as $i => $url) {
$res [$i]=curl_multi_getcontent ($conn [$i]);/Get page input
Curl_multi_remove_handle ($MH, $conn [$i]);
Curl_close ($conn [$i]);
}
Curl_multi_close ($MH);
foreach ($res as $k => $v) {
$k =str_pad ($k, 2,0);
echo "$k => $v <br>";
}
RunTime ($t);
#-----------Calculate Time function-------------
function GetTime () {
$TIME =explode ("", Microtime ());
$TIME = $TIME [1].substr ($TIME [0],1);
return $TIME;
}
function RunTime ($t, $l =3) {
$dif =gettime ()-$t;
Echo '. Number_format ($dif, $l);
}
?>
|