D
D
devblackhunter2022-02-18 22:47:13
C++ / C#
devblackhunter, 2022-02-18 22:47:13

Why doesn't libcurl run asynchronously?

Using curl_easy, each wrapped in std::async I download files.
3 asynchronous requests were created, but a problem arises when one of the requests stumbles upon a large file and starts downloading it, the whole program hangs from this. It turns out that asynchronous requests are not asynchronous at all.

using namespace std;

int allGameFileCount = 9999; // Здесь записывается кол-во нужных файлов
string allGameFiles[10000] = {}; // Здесь записаны названия файлов

bool downloadFile(const char* filename, const char* out)
{
    CURL* curl;
    curl = curl_easy_init();
    if (curl)
    {
        FILE* fp;
        fp = fopen(out, "wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteToFile);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        CURLcode result = curl_easy_perform(curl);

        long httpStatusCode = 0;
        curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStatusCode);
        if (result == CURLE_OK && httpStatusCode == 200)
        {
            // Success
            curl_easy_cleanup(curl);
            fclose(fp);
            return true;
        }
        fclose(fp);
    }
    curl_easy_cleanup(curl);
    return false;
}

int main() {
       future<void> f1 = async(launch::async, [] {
        if (downloadGameFile(allGameFiles[allGameFileCount].c_str(), allGameFiles[allGameFileCount].c_str()))
        {
          allGameFiles[allGameFileCount] = "";
          allGameFileCount--;
        }});

       future<void> f2 = async(launch::async, [] {
        if (downloadGameFile(allGameFiles[allGameFileCount-1].c_str(), allGameFiles[allGameFileCount-1].c_str()))
        {
          allGameFiles[allGameFileCount-1] = "";
          allGameFileCount--;
        }});

       future<void> f3 = async(launch::async, [] {
        if (downloadGameFile(allGameFiles[allGameFileCount-2].c_str(), allGameFiles[allGameFileCount-2].c_str()))
        {
          allGameFiles[allGameFileCount-2] = "";
          allGameFileCount--;
        }});
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question