V
V
vldud2018-04-25 14:00:24
PHP
vldud, 2018-04-25 14:00:24

How to avoid 100% CPU when using curl_multi_exec?

Good afternoon. The following code is used to bypass the url array:

$mh = curl_multi_init();

foreach ($urls as $url){
    $ch = curl_init();
    curl_setopt(
        $ch, 
        CURLOPT_URL, 
        $url
    );
  // запоминаем в массив, чтобы потом удалить cURL дескрипторы
    $arCh[$chIter] = $ch;
    curl_multi_add_handle($mh, $arCh[$chIter]);
    $chIter++;
}

// ассинхронные процессы, вешают CPU 100% 
$active = null;
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) == -1) {
        usleep(1);
    }
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
}

// убираем за собой
foreach ($arCh as $ch) {
    curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);

Actually this code leads to 100% CPU. The section marked with the comment "// asynchronous processes hang CPU 100% " was changed to, for example, this:
$running = null;
do {
    curl_multi_select($mh, 5);  
    curl_multi_exec($mh, $running);
} 
while ($running);

but it didn't help.
PHP 5.6.31
curl 7.59.0

Answer the question

In order to leave comments, you need to log in

2 answer(s)
X
xmoonlight, 2018-04-25
@xmoonlight

For the number of flows - you need to follow!
And do not stupidly add ...
Read here

A
Alexander Aksentiev, 2018-04-25
@Sanasol

Infinite loops always hang up everything... (and here there are as many as 3 of them)
You need to do normal delays or limit flows and delays.
The best option is not to suffer: https://github.com/guzzle/guzzle
There are multi, consoles, and asynchronous requests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question