gpt4 book ai didi

c++ - 如何将大对象复制到循环内的 omp 任务中?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:46:24 25 4
gpt4 key购买 nike

我正在使用一个 while 循环来启动多个 omp 任务。每个任务都需要复制一个相当大的对象(作为 firstprivate)。由于我的设置,大对象(在这个例子中是一个 vector )会被简单地复制两次:

struct bigStruct {
bool next() {
/* do something with m_bigVector */
}

std::vector<int> m_bigVector;
/* other (big) data members */
};

bigStruct s;

#pragma omp parallel
{
#pragma omp single
while (s.next()) {
auto obj = s.m_bigVector; //copy the first time

#pragma omp task firstprivate(obj) //copy the second time
{
/* do something with obj */
}
}
} //end parallel

gcc 优化 (-O3) 似乎没有以任何方式优化掉两个复制步骤。一个(不太优雅的)解决方案是使用显式 new/delete:

#pragma omp parallel
{
#pragma omp single
while (s.next()) {
auto obj_ptr = new std::vector<int>(s.m_bigVector); //copy once

#pragma omp task firstprivate(obj_ptr) //copy only the pointer
{
/* do something with obj */


delete obj_ptr;
}
}
} //end parallel

是否有更现代/优雅的方法来解决这个问题?也许是一种告诉任务移动对象而不是复制对象的方法?请注意,我不想复制整个 bigStruct,因为它包含其他大数据成员。

最佳答案

好消息!

A firstprivate variable must not have a reference type.

自 OpenMP 4.5 (2015) 起已过时。目前没有这样的限制。有一个要求:

If a list item in a firstprivate clause on a worksharing construct has a reference type then it must bind to the same object for all threads of the team.

但这并不适用 - task 构造不是工作共享构造,无论如何多线程都不会遇到。

要充分理解标准的要求:

(关于列表项私有(private)化)

If the type of a list item is a reference to a type T then the type will be considered to be T for all purposes of this clause.

A new list item of the same type, with automatic storage duration, is allocated for the construct. The storage and thus lifetime of these list items last until the block in which they are created exits.

For each variable of class type:

• If the firstprivate clause is not on a target construct then a copy constructor is invoked to perform the initialization

所以你可以安全地做:

auto& obj = s.m_bigVector;
#pragma omp task firstprivate(obj) // call copy ctor once

很遗憾,你不能

  • 使用 const auto& 因为 obj 的类型将是 const,因为只有引用被删除。
  • 将 obj 移动到 firstprivate 声明中。那会很好,但仅适用于只有单个线程实际遇到数据共享子句的任务。

关于c++ - 如何将大对象复制到循环内的 omp 任务中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57038722/

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