【问题标题】:How to parallelize a function, that uses some variable如何并行化使用某些变量的函数
【发布时间】:2018-05-02 10:40:04
【问题描述】:

我有一个函数,它会生成随机 URL,然后尝试下载文件。

void tryURL()
{
    randURL.clear();
    for (unsigned short i = 0; i < urlLength; i++)  {
    randURL = randURL + (alphabet[(int)((double)rand() / (RAND_MAX + 1) * alphabetLength)]);
    }
    wcout << randURL << endl;
    HRESULT getImg = URLDownloadToFile(NULL, LPCWSTR( (beginURL + randURL + endURL).c_str() ), LPCWSTR( (randURL + L"/" + endURL).c_str() ), 0, NULL);
    if (SUCCEEDED(getImg))
    {
    wcout << L"Success" << endl;
    }
}

如果我正常执行这个功能,它工作正常:

tryURL();
0ybOAt
tryURL();
lTPKaR
tryURL();
Ivi05m
...

但是,我需要在那个时候反复运行这个函数。 我试过这个:

thread threads[10];

for (int i = 0; i < 10; ++i) {
    threads[i] = thread(tryURL);
}

for (int i = 0; i < 10; ++i) {
    threads[i].join();
}

它总是返回相同的值

0ybOAt0ybOAt
0ybOAt

0ybOAt0ybOAt

0ybOAt
0ybOAt0ybOAt
0ybOAt
0ybOAt

有时甚至连endl都不出现。

我该如何解决?我认为,它坏了,因为总是使用相同的变量 randURL,但我不知道如何避免这一点。

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

    不要使用相同的变量,而是使tryURL 返回 URL:

    // assuming that URLs are strings
    std::string tryURL() { /* ... */ }
    

    然后,创建一个std::future&lt;std::string&gt; 的向量来表示将返回 URL 的异步计算:

    std::vector<std::future<std::string>>> futures;
    futures.reserve(10);
    
    for (int i = 0; i < 10; ++i) 
    {
        futures.emplace_back(std::async(std::launch::async, tryURL));
    }
    

    最后,在主线程中消费 URL:

    for(auto& f : futures) 
    {
        consume(f.get());
    } 
    

    【讨论】:

    • 无法在 VC17 上运行此代码。 launch_async 替换为 launch::async,但未找到使用命令。你能解决它吗?
    • @megapro17: consume 只是一个例子。这就是你的逻辑应该去的地方。
    【解决方案2】:

    StackOverflow 上的其他问题提供了一些线索:

    对 rand() 问题的简单修复是在主线程中生成 URL:s 并将它们传递给线程。

    void tryURL(std::wstring URL)
    ...
    // TODO: Set randURL to a random URL
    threads[i] = thread(tryURL, randURL);
    

    【讨论】:

    • 好的,我修好了兰特。但我的程序只运行 4 个线程。我不明白为什么。我尝试了更多,但一次只执行了 4 个线程。另外,我有 4 核 CPU。 for (int i = 0; i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 2015-02-25
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    相关资源
    最近更新 更多