OpenMP 线程执行重复工作/去同步

发布于 2025-01-20 23:27:32 字数 1235 浏览 1 评论 0原文

我正在尝试使用 OpenMP 并行化递归函数(它通过基本上尝试所有可能的路径/回溯来解决 Knight's Tour 问题)。在大多数情况下,OpenMP 任务应该可以完成这项工作,但线程有时会重复工作/不同步,从而导致程序挂起。 这是函数调用:

#pragma omp parallel num_threads(8)
    {
      #pragma omp single
      {
        if(!findtour(*this, 0)) {
          cout << "No solutions found\n";
        }
      }
    }

这是函数本身:

bool tour::findtour(tour& T, int imove) {
  if(imove == (size*size - 1)) return true;
  // make a move
  int cx = T.sx;
  int cy = T.sy;
  int cs = T.size;
  for (int i = 0; i < 8; ++i) {
    int tcx = cx + movimento[i][0];
    int tcy = cy + movimento[i][1];
    // Is this a valid move?
    // Has this place been visited yet
    if ((tcx >= 0) &&  (tcy >= 0)  &&  (tcx < cs) &&  (tcy < cs) && (T.board[tcx][tcy] == -1)) {
      tour temp(T);
      temp.board[tcx][tcy] = imove+1;
      temp.sx = tcx;
      temp.sy = tcy;
      #pragma omp task firstprivate(T, imove, temp)
      {
        if(findtour(temp, imove+1)) {
          cout << temp << endl;
          exit(1);
        }
      }
    }
  }
  #pragma omp taskwait
  return false;
}

我无法说出到底是什么导致了问题,因为我已经尝试更改许多共享/私有变量,因此我们将不胜感激。

I'm trying to parallelize a recursive function (which solves the Knight's Tour problem by basically trying every possible path/backtracking) using OpenMP. OpenMP tasks should do the job in most cases, but the threads are ocasionally doing repeated work/desynchronizing which causes the program to hang.
This is the function call:

#pragma omp parallel num_threads(8)
    {
      #pragma omp single
      {
        if(!findtour(*this, 0)) {
          cout << "No solutions found\n";
        }
      }
    }

And this is the function itself:

bool tour::findtour(tour& T, int imove) {
  if(imove == (size*size - 1)) return true;
  // make a move
  int cx = T.sx;
  int cy = T.sy;
  int cs = T.size;
  for (int i = 0; i < 8; ++i) {
    int tcx = cx + movimento[i][0];
    int tcy = cy + movimento[i][1];
    // Is this a valid move?
    // Has this place been visited yet
    if ((tcx >= 0) &&  (tcy >= 0)  &&  (tcx < cs) &&  (tcy < cs) && (T.board[tcx][tcy] == -1)) {
      tour temp(T);
      temp.board[tcx][tcy] = imove+1;
      temp.sx = tcx;
      temp.sy = tcy;
      #pragma omp task firstprivate(T, imove, temp)
      {
        if(findtour(temp, imove+1)) {
          cout << temp << endl;
          exit(1);
        }
      }
    }
  }
  #pragma omp taskwait
  return false;
}

I can't tell what exactly is causing the issue as I have tried changing many of the shared/private variables so any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文