c++用线程并行处理vector的每个元素



我对现代c++多线程有点陌生,我想知道并行处理向量的每个元素的正确方法是什么。更具体地说,假设如下情况:

struct Neighbor
{
int idx;
float score;
};
struct Cluster
{
std::vector<int> cameras;
std::unordered_map<int, std::vector<Neighbor>> neighbors;
};
class Test
{
std::vector<Cluster> clusters;
void DoSomething();
void DoSomethingForCluster(const int i);
};

我想并行处理集群向量的每个元素(即填充内部的映射),因为每个元素之间没有依赖关系。我的第一个猜测是尝试这样做:

void Test::DoSomething()
{
std::vector<std::thread> th_vec;
for (int i = 0; i < clusters.size(); i++)
{
th_vec.push_back(std::thread(&Test::DoSomethingForCluster, this, i));
}
for (auto& t : th_vec)
{
t.join();
}
}
void Test::DoSomethingForCluster(const int i)
{
for (const auto& cam : clusters[i].cameras)
{
std::vector<Neighbor> n;
// Do something to fill the vector n
clusters[i].neighbors.insert(std::make_pair(cam, n));
}
}

代码构建和运行顺利,但我想知道是否有更好或更有效的方法来完成这类任务。例如,为每个元素启动一个线程是否有意义?如有任何建议或帮助,我都非常感激,谢谢你。

我自己没有这样做过,但我认为您可以使用for_each和执行策略来完成此操作:

std::for_each(std::execution::parallel_policy, clusters.begin(), clusters.end() []() {....} );

让库决定创建多少个线程。

你可以谷歌一下"c++执行策略";以获得更多的信息。

最新更新