c++在派生函数中启动OMP线程

标签 c++ multithreading openmp

假设我有一个基类,它有一个带有两个 OMP 线程的虚函数:

class Parent {
 public:
  Parent() {}
  ~Parent() {}
  virtual void f() {
  #pragma omp parallel sections
    {
  #pragma omp section
      {
         // do_something_1();
      }
  #pragma omp section
      {
         // do_something_2();
      }
    }
  }
}

然后我有一个这样的派生类:

class Child : public Parent {
 public:
  Child() {}
  ~Child() {}
  void f() {
    Parent::f();
    // Other thread OMD
  }
}

我希望父类的两个线程和子类的线程在最后运行,但它不工作。这种设计甚至可能吗?

最佳答案

问题是 OpenMP 指令在 Parent 的虚函数中,所以 在您的派生类中看不到。当您在派生类中调用父代码时 这提出了两种可能的解决方案,两者各有优缺点。

版本 1 将 Parent 的操作保密,但只能额外扩展一次 水平。

class Parent {
 public:
  void f() {
  #pragma omp parallel sections
    {
  #pragma omp section
      {
         // do_something_1();
      }
  #pragma omp section
      {
         // do_something_2();
      }
  #pragma omp section
      {
         this->f_impl();
      }
    }
  }
  private:
    virtual void f_impl() {}; // do nothing placeholder

}

class Child : public Parent {
  private:
    void f_impl() override;
}

版本 2 可以无限期扩展,但需要公开每个父级的内部结构。

class Parent {
 public:
  virtual void f() {
  #pragma omp parallel sections
    {
  #pragma omp section
      {
         f_impl1();
      }
  #pragma omp section
      {
         f_impl2();
      }
    }
  }
  protected:
    void f_impl1();
    void f_impl2();

}

class Child : public Parent {
 public:
  virtual void f() {
  #pragma omp parallel sections
    {
  #pragma omp section
      {
         f_impl1();
      }
  #pragma omp section
      {
         f_impl2();
      }
  #pragma omp section
      {
         f_impl3();
      }
    }
  }
  protected:
    void f_impl3();
}

class Child2 : public Child {
 public:
  virtual void f() {
  #pragma omp parallel sections
    {
  #pragma omp section
      {
         f_impl1();
      }
  #pragma omp section
      {
         f_impl2();
      }
  #pragma omp section
      {
         f_impl3();
      }
  #pragma omp section
      {
         f_impl4();
      }
    }
  }
  protected:
    void f_impl4();
}

关于c++在派生函数中启动OMP线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47479298/

相关文章:

C++ OpenMP for循环全局变量问题

c++ - 为什么此代码使用 openMP 提供 SIGABRT?

c++ - 如果忽略返回值,如何发出警告?

c++ - 堆栈列表调试断言失败 C++

java - 在android中,如何将数据加载到它自己的线程中?

windows - 将 Windows 手动重置事件移植到 Linux?

c - OpenMP 并行可减慢我的代码速度(C 语言)

c++ - 使用C++20 Concept约束模板参数

c++ - 在 Mingw-w64 中使用 %I64u 得到奇怪的结果

python - 来自 tkinter 应用程序的多线程