c++ - OpenMP 问题

标签 c++ class openmp

我想在类成员函数中并行化一个循环。但是代码中有两个错误:

class myclass  
{  
public:  

int _k;  

void f(int nb_examples, int nb_try)  
{  
      int i;  
      int ks[nb_try];  
      // assignment to elements in ks  
      omp_set_num_threads(_nb_threads);  
    #pragma omp parallel shared(ks) private(i, _k) // error: ‘myclass::_k’ is not a variable in clause ‘private’  
      {  
    #pragma omp for schedule(dynamic) nowait  
        for(i=0; i < nb_try; i ++){  
          _k = ks[i];  
          if (_k > nb_examples)  break;// error: break statement used with OpenMP for loop  
          // operations on _k  
        }  
      }   
}  
}

如何解释这些错误并解决问题?谢谢和问候!

最佳答案

对于第二个错误,由于并行性质,OpenMP 规范不允许您跳出并行 for 循环或抛出异常。相反,请参阅此博客上的变通解决方案:http://www.thinkingparallel.com/2007/06/29/breaking-out-of-loops-in-openmp/

对于第一个错误,我花了一些时间来挖掘实际发生的事情 - 我认为这可以解释它:

Private variables must not have reference type, since it will cause concurrent shared memory access. Although the variables will be private, the variables will still address the same memory fragment. Class instances declared as private must have explicit copy constructor, since an instance containing references will be copied incorrectly otherwise.

来自 http://www.viva64.com/content/articles/parallel-programming/?f=32_OpenMP_traps.html&lang=en&content=parallel-programming

基本上我认为您可以将类级变量用作私有(private)变量而不复制它们。有什么理由不能在函数范围内使用变量吗?

关于c++ - OpenMP 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2173569/

相关文章:

c++ - `std::timed_mutex` 的有效用例?

c++ - 为什么不允许将 Derived T::* 转换为 Base T::*?

c - OpenMP 错误 : 'X' is predetermined 'shared' for 'private'

c++ - 用于创建唯一命名的 OpenMP 临界区的宏?

C、OpenMP、更改计划类型、setenv

c++ - 如何在centos中的c中从IP获取以太网适配器名称

c++ - 无法从好友类访问成员

c++ - unordered_map 的问题

java - 按名称访问对象变量和方法

c++ - 将 C++ 对象传递给它自己的构造函数是否合法?