gpt4 book ai didi

c++ - 如何在剩余线程完成工作时处理任务

转载 作者:行者123 更新时间:2023-11-28 00:34:40 26 4
gpt4 key购买 nike

假设我有一个运行某些操作的 OpenMP 2.0 for 循环:

#pragma omp parallel for schedule(static)
for (int i = 0; i < lim; ++i)
{
// do something thread-safe
}
threadSafeFunc();

unSafeFunc();

仿函数 threadSafeFunc 是完全线程安全的,因此我不想在所有这些迭代完成后连续运行它,而是希望获得第一个完成任务分配的线程,从 OpenMP 循环到开始处理它,然后让所有线程在串行执行 unSafeFunc 之前等待。

我该怎么做?

最佳答案

这可能是您特定问题的解决方案:

#pragma omp parallel 
{ // #1
#pragma omp for schedule(static) nowait
for (int i = 0; i < lim; ++i) // #2
{
// do something thread-safe
} // No implied barrier bue to the nowait clause
#pragma omp single
{ // #3
threadSafeFunc();
} // Implied barrier
} // End of parallel region
unSafeFunc();

想法很简单:首先在#1 中打开一个parallel 区域。在这个平行区域内,您使用两个工作共享结构:

  1. #2 处的循环结构
  2. #3 处的单个结构

循环构造(standard 的第 2.7.1 节)有一个 nowait 子句,用于删除循环结束时的隐式屏障。然后是 single 构造(第 2.7.3 节):

... specifies that the associated structured block is executed by only one of the threads in the team (not necessarily the master thread), in the context of its implicit task. The other threads in the team, which do not execute the block, wait at an implicit barrier at the end of the single ...

这两个构造的组合确保了第一个在循环中完成其工作的线程将进入single构造并执行threadSafeFunc()。然后所有线程将在隐含的障碍处同步并加入 master 线程。此时只有 master 线程会继续执行 unSafeFunc()

关于c++ - 如何在剩余线程完成工作时处理任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21422065/

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