c++ - 新算子+OpenMP动态调度子句

标签 c++ arrays multithreading openmp dynamic-memory-allocation

我一直在使用 C++ 代码来执行量子化学、原子和分子任务,其中隐含大量使用数组(1D、2D、3D 等)的工作。我有一个名为 array 的完整类来处理这个问题。当然,从一开始,最基本的成员函数就是那些为这些数组动态分配内存、调整大小或删除它们的函数。

data = new double **[row]();
#pragma omp for schedule(static) nowait
for(unsigned int i = 0; i < row; ++i)
{
    data[i] = new double *[column]();
}

现在我正在做的是使用 OpenMP 加速这些例程。对于大部分例程,我一直在使用 schedule(static) nowait 子句将我的循环划分为 step/threads block ,因为这些 block 花费的时间几乎相同由他们的线程处理的时间。

但对于像上面那样的循环,多次调用 new 运算符,我有一种(不好的)感觉,即这些循环的 block 在它们的线程中执行的时间不同,从某种意义上说,我应该考虑改为应用 schedule(dynamic, chunk_size)

你们同意吗?动态分配不是这么简单的任务,而且可能很昂贵,因此动态分配 block 的执行时间可能不同。

实际上,我不确定我是否没有犯任何关于堆栈碎片或类似问题的错误。欢迎提出建议。

PS.: 我正在使用 nowait 子句来尽量减少隐式障碍的瓶颈。

最佳答案

如果您使用默认的 new,您的特定循环可能不会提供太多并行机会运算符,因为堆是一个单一的资源,对它的访问需要通过互斥锁进行序列化。但是,假设您有其他希望使用 OpenMP 的循环,以下内容应该有所帮助。

来自 OpenMP 3.1 specification :

static When schedule(static, chunk_size) is specified, iterations are divided into chunks of size chunk_size, and the chunks are assigned to the threads in the team in a round-robin fashion in the order of the thread number.

When no chunk_size is specified, the iteration space is divided into chunks that are approximately equal in size, and at most one chunk is distributed to each thread. Note that the size of the chunks is unspecified in this case.

dynamic When schedule(dynamic, chunk_size) is specified, the iterations are distributed to threads in the team in chunks as the threads request them. Each thread executes a chunk of iterations, then requests another chunk, until no chunks remain to be distributed.

Each chunk contains chunk_size iterations, except for the last chunk to be distributed, which may have fewer iterations.

When no chunk_size is specified, it defaults to 1.

在您的情况下,您没有指定 chunk_size,因此每个任务的迭代次数未指定。

一般来说,我更喜欢对线程数量和每个任务执行的迭代次数进行一些控制。我发现(在 Windows 上,使用 mingw-w64 编译),任务开始新工作 block 的开销很大,因此给它们尽可能大的 block 是有益的。我倾向于使用动态(尽管我可以将静态用于固定执行时间的任务),并将 chunk_size 设置为循环计数除以线程数。在您的情况下,如果您怀疑任务执行时间不均匀,您可以将其除以 2 或 4。

// At the top of a C++ file:
static int NUM_THREADS = omp_get_num_procs();

// Then for your loop construct (I'm using a combined parallel for here):
#pragma omp parallel for num_threads(NUM_THREADS) \
   schedule(dynamic, row / NUM_THREADS / 2)
for(unsigned int i = 0; i < row; ++i)
{
   data[i] = new double *[column]();
}

另请注意,如果您未设置 num_threads,则默认值为 nthreads-var,它由 omp_get_max_threads 确定.

关于 nowait条款,显然要确保你没有使用 data在你的 loop 构造之外。我在上面使用了组合并行循环结构,这意味着 nowait无法指定。

关于c++ - 新算子+OpenMP动态调度子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23247336/

相关文章:

c++ - 跨平台通用C++ RPC库

c++ - 返回包含此类对象的结构的类静态方法

javascript - 如何从数组中获取单个字段

c - 退出线程时检测到堆栈崩溃

c++ - 在 OSX 中为 Qt 5.5 安装第三方模块

c++ - 是否可以为所有子类创建一个实例?

c# - 计算/排序文本文件中的字符

java - 从 JToggleButton 检索信息时遇到问题?(匹配游戏)

c# - Interlocked.CompareExchange 如果不相等?

java - 易变和同步