gpt4 book ai didi

c++ - 如何停止 OpenMP 2.0 的并行区域

转载 作者:行者123 更新时间:2023-11-30 03:18:52 33 4
gpt4 key购买 nike

我正在寻找一种更好的方法来取消我的线程。在我的方法中,我使用一个共享变量,如果设置了这个变量,我就抛出一个继续。这可以快速完成我的线程,但理论上线程会不断产生和结束,这似乎并不优雅。那么,有没有更好的方法来解决这个问题(我的 OpenMP 不支持 break)?

我必须使用 Visual,所以我的 OpenMP Lib 已经过时,没有办法解决这个问题。因此,我认为 #omp cancel 不会起作用

int progress_state = RunExport;
#pragma omp parallel
{
#pragma omp for
for (int k = 0; k < foo.z; k++)
for (int j = 0; j < foo.y; j++)
for (int i = 0; i < foo.x; i++) {
if (progress_state == StopExport) {
continue;
}

// do some fancy shit

// yeah here is a condition for speed due to the critical
#pragma omp critical
if (condition) {
progress_state = StopExport;
}
}
}

最佳答案

您应该采用“如果请求取消,则在所有剩余迭代中继续”的简单方法。这可能只是最外层循环中的第一次检查(假设您有多个嵌套循环,这可能不会有任何可测量的开销)。

std::atomic<int> progress_state = RunExport;

// You could just write #pragma omp parallel for instead of these two nested blocks.
#pragma omp parallel
{
#pragma omp for
for (int k = 0; k < foo.z; k++)
{
if (progress_state == StopExport)
continue;

for (int j = 0; j < foo.y; j++)
{
// You can add break statements in these inner loops.
// OMP only parallelizes the outermost loop (at least given the way you wrote this)
// so it won't care here.
for (int i = 0; i < foo.x; i++)
{

// ...

if (condition) {
progress_state = StopExport;
}
}
}
}
}

一般来说,OMP 不会突然生成新线程或结束现有线程,尤其是在一个并行区域内。这意味着与运行更多微小迭代相关的开销很小。鉴于您的情况下的默认调度很可能是 static,这更是如此,这意味着每个线程立即知道其开始和结束索引。其他调度模式必须在每次迭代(或每隔几次迭代)调用 OMP 运行时以请求更多工作,但这不会发生在这里。编译器基本上会看到线程工作的代码:

// Not real omp functions.
int myStart = __omp_static_for_my_start();
int myEnd = __omp_static_for_my_end();
for (int k = myStart; k < myEnd; ++k)
{
if (progress_state == StopExport)
continue;

// etc.
}

您可以尝试非原子线程本地“我应该取消吗?”以 false 开头且只能更改为 true 的标志(编译器可能会理解并将其折叠到循环条件中)。但我怀疑无论哪种方式,您都会看到显着的开销,至少在 int 无论如何都是原子的 x86 上是这样。

which seems not elegant

OMP 2.0 并没有在优雅方面大放异彩。我的意思是,遍历 std::vector 需要至少一个 static_cast 来消除 signed -> unsigned 转换警告。因此,除非您有此模式导致性能问题的具体证据,否则没有理由不使用它。

关于c++ - 如何停止 OpenMP 2.0 的并行区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54293086/

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