Understanding PHP multi_curl_exec loops
In the PHP curl_multi_exec manual, a strange 3 loops are given as an example:
1
2
3
4
5
6
7
8
9
10
11
12
|
<?php
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
|
I was wondering why we needed so many while loops as opposed to a simple one such as:
1
2
3
4
|
<?php
do {
curl_multi_exec($master,$running);
} while($running > 0);
|
What I have found is mostly due to prevent making unnecessary calls to curl_multi_exec. Here the same first snippet with comments:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?php
// Launch the requests. This is non blocking,
// and returns CURLM_CALL_MULTI_PERFORM as long as there is something to do
// (in this case, launch the remaining requests)
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
// Actually do the fetching job
while ($active && $mrc == CURLM_OK) {
// This function is blocking and waits until there is activity
if (curl_multi_select($mh) != -1) {
do {
// Run the connections
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
|
With those loops, we only run curl_multi_exec when something changed. The second snipped would make unnecessary calls to this function and shoot up our CPU usage.