std :: async - 参数向量已损坏

nab*_*yan 3 c++ multithreading asynchronous vector c++11

我想将一个向量分成小向量,在一个线程上分别处理它们,然后合并它们.我想std::async用于创建线程,我的代码看起来像这样

void func(std::vector<int>& vec)
{
   //do some stuff
}

// Calling part
std::vector<std::future<void>> futures;
std::vector<std::vector<int>> temps;
for (int i = 1; i <= threadCount; ++i)
{
    auto& curBegin = m_vec.begin() + (i - 1) * size / threadCount;
    auto& curEnd = m_vec.begin() + i * size / threadCount;
    std::vector<int> tmp(curBegin, curEnd);
    temps.push_back(std::move(tmp));

    futures.push_back(std::async(std::launch::async, &func, std::ref(temps.back())));
}
for (auto& f : futures)
{
    f.wait();
}

std::vector<int> finalVector;
for (int i = 0; i < temps.size() - 1; ++i)
{
    std::merge(temps[i].begin(), temps[i].end(), temps[i + 1].begin(), temps[i + 1].end(), std::back_inserter(finalVector));
}
Run Code Online (Sandbox Code Playgroud)

m_vec是主矢量,它被分成小矢量.问题是当我传递一个向量时func(),在函数中它变为无效,大小为0或无效元素.但是当我尝试调用该函数时,std::async一切正常.

那有什么问题std::async,我应该做些什么特别的事情?

感谢您的时间!

Pio*_*cki 5

如果在迭代扩展向量时发生重新分配temps,则std::ref(temps.back())线程很可能正在引用已经失效的内存区域.您可以通过在连续push_backs 之前保留内存来避免重定位:

temps.reserve(threadCount);
Run Code Online (Sandbox Code Playgroud)