gpt4 book ai didi

c++ - 用一个线程做一个部分,用多个线程做一个for循环

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

我正在使用 OpenMP,我想生成线程,以便一个线程执行一段代码并完成,与运行并行 for 循环迭代的 N 个线程并行。

执行应该是这样的:

Section A (one thread)       ||      Section B (parallel-for, multiple threads)
| || | | | | | | | | | |
| || | | | | | | | | | |
| || | | | | | | | | | |
| || | | | | | | | | | |
| || | | | | | | | | | |
V || V V V V V V V V V V

我不能只用 #pragma omp once 编写并行 for,因为我不希望执行 A 部分的线程执行 for 循环。

我试过这个:

#pragma omp parallel sections {
#pragma omp section
{
// Section A
}

#pragma omp section
{
// Section B;
#pragma omp parallel for
for (int i = 0; i < x; ++i)
something();
}
}

但是,parallel-for 总是只用一个线程执行(我知道是因为我在循环体中打印了 omp_get_thread_num() 并且它们都是相同的数字,要么是 1 要么是 0,具体取决于第二个并行部分在两者中的哪个线程上执行)。

我也试过

#pragma omp sections {
#pragma omp section
{
// Section A
}

#pragma omp section
{
// Section B;
#pragma omp parallel for
for (int i = 0; i < x; ++i)
something();
}
}

这允许 for 循环与多个线程一起执行,但它使各部分不平行,并且第一部分在第二部分之前按顺序执行。

我需要的是两种方法的组合,其中 for 循环的每次迭代和第一部分都并行运行。

最佳答案

嵌套并行性必须显式设置,因为在大多数实现中默认情况下它是禁用的。站在OpenMP 4.0标准,你必须设置OMP_NESTED环境变量:

The OMP_NESTED environment variable controls nested parallelism by setting the initial value of the nest-var ICV. The value of this environment variable must be true or false. If the environment variable is set to true, nested parallelism is enabled; if set to false, nested parallelism is disabled. The behavior of the program is implementation defined if the value of OMP_NESTED is neither true nor false.

以下行应该适用于 bash:

 export OMP_NESTED=true

此外,正如@HristoIliev 在下面的评论中指出的那样,您很可能想要设置 OMP_NUM_THREADS 环境变量来调整性能。引用标准:

The value of this environment variable must be a list of positive integer values. The values of the list set the number of threads to use for parallel regions at the corresponding nested levels.

这意味着应该将 OMP_NUM_THREADS 的值设置为类似于 n,n-1,其中 n 是 CPU 内核的数量。例如:

export OMP_NUM_THREADS=8,7

对于 8 核系统(从下面的评论中复制的示例)。

关于c++ - 用一个线程做一个部分,用多个线程做一个for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23178183/

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