'Correct usage of curl async functions - curl_multi_*

I am trying to do around 50 async soap requests using curl_multi from server 1 to server 2.

In the end, the responses take around 18 seconds for all the requests to complete.

Also, each response from server 2 has an execution time in the response so i know how much time it took server 2 to process the request and send back the response.

If i look at the 50 responses, the longest took around 1.6 seconds, an average of 1-1.2 seconds. So, should not the response time be around 1.6 seconds for all the requests instead of 18 seconds.

I am trying to figure out what i am missing, to get the requests to be truely asynchronous.

 $curlHandles = [];
    $responses = [];

    foreach ($requests as $request) {
        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curlHandle, CURLOPT_HTTPAUTH, $this->getCurlAuth());
        curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $this->getHeaders());
        curl_setopt($curlHandle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($curlHandle, CURLOPT_POST, true);
        curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $request);
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curlHandle, CURLOPT_USERPWD, $this->getUserPassword());
        $curlHandles[] = $curlHandle;
    }

    //create the multiple cURL handle
    $multiCurlHandle = curl_multi_init();

    //set curl multi options
    curl_multi_setopt($multiCurlHandle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);


    //add the handles
    foreach ($curlHandles as $curlHandle) {
        curl_multi_add_handle($multiCurlHandle, $curlHandle);
    }
    $start = microtime(true);
    //execute the multi handle
    do {
        $status = curl_multi_exec($multiCurlHandle, $active);
        if ($active) {
            curl_multi_select($multiCurlHandle);
        }
    } while ($active && $status == CURLM_OK);

    //close the handles
    foreach ($curlHandles as $curlHandle) {
        curl_multi_remove_handle($multiCurlHandle, $curlHandle);
    }

    curl_multi_close($multiCurlHandle);

    // get all responses
    foreach ($curlHandles as $curlHandle) {
        $responses[] = curl_multi_getcontent($curlHandle);
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source