我有一个函数,可以生成随机 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,但我不知道如何避免这个。
最佳答案
不要使用相同的变量,而是使用 tryURL
返回 URL:
// assuming that URLs are strings
std::string tryURL() { /* ... */ }
然后,创建 std::future<std::string>
的 vector 表示将返回 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());
}
关于c++ - 如何并行化使用某些变量的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47371215/