gpt4 book ai didi

c++11 - 将 OpenMP 与 C++11 基于范围的 for 循环结合使用?

转载 作者:行者123 更新时间:2023-12-02 19:27:52 25 4
gpt4 key购买 nike

这样做有什么反迹象吗?或者行为是否明确指定?

#pragma omp parallel for
for(auto x : stl_container)
{
...
}

因为OpenMP规范似乎只对c++98有效,但我猜由于C++11线程可能会有更多不兼容性,这里没有使用这些线程。我仍然想确定一下。

最佳答案

OpenMP 4.0 规范已于几天前最终确定并发布 here 。它仍然要求并行循环应采用规范形式(§2.6,p.51):

for (init-expr; test-expr; incr-expr) structured-block

该标准允许在所有表达式中使用提供随机访问迭代器的容器,例如:

#pragma omp parallel for
for (it = v.begin(); it < v.end(); it++)
{
...
}

如果您仍然坚持使用 C++11 语法糖,并且处理 STL_container 的每个元素需要(相对)大量时间,那么您可以使用单生产者任务模式:

#pragma omp parallel
{
#pragma omp single
{
for (auto x : stl_container)
{
#pragma omp task
{
// Do something with x, e.g.
compute(x);
}
}
}
}

任务处理会产生一定的开销,因此如果 compute(x); 只需很少的时间即可完成,那么使用此模式就没有意义。

关于c++11 - 将 OpenMP 与 C++11 基于范围的 for 循环结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17848521/

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