gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:11:05 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com