Example of a multithreaded query for PHP curl_multi

Source: Internet
Author: User

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

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.