c++ - 如何并行化使用某些变量的函数

标签 c++ multithreading

我有一个函数,可以生成随机 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/

相关文章:

c++ - 尝试包装函数返回值时出现 "<class name> does not provide a call operator"错误

c++ - dlsym() + RTLD_NEXT 在 Ubuntu 20.04 上无法正常工作

c++ - int x{}; 之间有区别吗?和int x = 0;?

c# - delegate.BeginInvoke 和在 C# 中使用 ThreadPool 线程的区别

java - ScheduledExecutorService 一线程多任务

c++ - 如何拥有类似于 unsigned char 的类型,但不允许别名?

c++ - 访客模式添加新功能

multithreading - 如何使信号量超时

ios - 当在另一个线程上执行 block 时,我应该将 'volatile' 与 '__block' 限定符一起使用吗?

c# - .Net中的Dictionary在并行读写时是否有可能导致死锁?