【发布时间】: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