Mike
Mike

Reputation: 81

When using curl_multi_* there is around 20 iterations for one request despite curl_multi_select use. Why?

From the documentation for the curl_multi_select:

Blocks the execution of the script until a cURL handle attached to the cURL multi handle would be able to make progress on the next call to curl_multi_exec() or until the timeout strikes (whichever comes first).

I don't fully understand how this function works and why it doesn't block execution of the code until one request is made. It blocks execution, but not completely...

Here is my code:

$urls = [
    'https://google.com',
];

$mh = curl_multi_init();
foreach ($urls as $i => $url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_multi_add_handle($mh, $ch);
}

$timeout = 5;
$loop = 0;
$unfinishedHandles = 0;
do {
    $loop++;
    $status = curl_multi_exec($mh, $unfinishedHandles);
    if ($unfinishedHandles > 0) {
        curl_multi_select($mh, $timeout);
    }

    while (($info = curl_multi_info_read($mh)) !== false) {
        if ($info['msg'] === CURLMSG_DONE) {
            $handle = $info['handle'];
            curl_multi_remove_handle($mh, $info['handle']);
            if ($info['result'] === CURLE_OK) {
                $chInfo = curl_getinfo($info['handle']);
                echo "Request to {$chInfo['url']} completed", PHP_EOL;
            }
        }
    }
} while ($unfinishedHandles);

curl_multi_close($mh);

echo 'Iterations: ', $loop, PHP_EOL;

Result:

Request to https://google.com/ completed
Iterations: 15

Why there is 15 iterations? If I comment curl_multi_select call there will be 125779 iterations. If I decrease the $timeout, I will also get more iterations. That's understandable. So the function works, but why it is 15-20? I can't understand...

Upvotes: 2

Views: 59

Answers (0)

Related Questions