c++ - 在 C++ 中更新 vector 或列表的多个调用异步

标签 c++ asynchronous vector future

我陷入了这样的多个异步问题 示例:

void updateList(vector<int> &list, int value){
  list.push_back(value);
}

int main(){
   vector<future<void>> asyncTasks;
   vector<int> list;
   for(int i = 0; i < 10; i ++){
      asyncTasks.push_back(async(launch::async, updateList,i ));
   }

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

问题是有时它会抛出有关插入暴力的错误。

你能给我一些想法吗?

最佳答案

问题是你在 updateList 中同时做两件事:

  1. 根据给定的索引计算一个值(通过计算我的意思是只使用它)
  2. 向容器添加值

并行执行第二个操作没有多大意义,因为您必须在容器上进行序列化,否则会出现数据竞争,这就是您出错的原因。

void updateList(vector<int> &list, int value){
  list.push_back(value); //< Data race-> Undefined behavior -> Sometimes Crash 
}

但是我们可以做一些容易并行的事情,即 1. 一个值的计算。 如果我们只是在容器中添加虚拟零,首先,我们可以修改容器中的元素,即 std::vector,因为我们不修改容器本身,例如计数或订单,只有它的成员。

所以之后你可以并行计算,但为什么不直接使用新的并行算法来为我们做呢?所以我添加了第二个解决方案。

此外,阿姆达尔定律还发现您的工作由无法并行的工作和可以并行的工作组成。

#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <execution>
#include <future>


//Your modified solution
void updateList(std::vector<int> &list, int value){
    const auto index = value;
    //Do the heavy stuff here
    list[index]  = value;
}

int main(){

    std::vector<int> list(10);
    std::vector<std::future<void>> asyncTasks;
    for(int i = 0; i < 10; i ++){
        asyncTasks.emplace_back(std::async(std::launch::async, &updateList, std::ref(list), i));
    }
    for(auto &f : asyncTasks){
        f.get();
    }

    std::for_each(list.begin(),list.end(), [](auto v) {std::cout << v << " ";});
    std::cout << "\n";
}


//Better solution:

int heavy_work_calculation(int input) {
    //Do the heavy stuff here
    return input;
}

int main(){

    std::vector<int> list(10);
    std::iota(list.begin(), list.end(), 0);
    std::transform(std::execution::par_unseq, list.begin(), list.end(),
                    list.begin(), heavy_work_calculation);

    std::for_each(list.begin(),list.end(), [](auto v) {std::cout << v << " ";});
    std::cout << "\n";
}

关于c++ - 在 C++ 中更新 vector 或列表的多个调用异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57781478/

相关文章:

c++ - 带有 __256i vector 的意外 _mm256_shuffle_epi

c++ - 我什么时候应该使用 QThread::HighestPriority

java - 带有异步 Servlet 的 JAX-WS

java - 如何使用异步套接字?

c++ - vector pop_back 导致堆缓冲区溢出错误

c++ - 从 vector/ map 中删除值

c++ - 如何在一个类中有一个多维可变维度数组?

c++ - 如何检查字符数组是否组合成某些连续的字符列表?

c++ - 从程序集引导加载程序调用 C++

asynchronous - Mono 下的 F# 任务并行性不会 "appear"并行执行