gpt4 book ai didi

c++ - OpenMP 问题

转载 作者:行者123 更新时间:2023-11-30 01:00:43 25 4
gpt4 key购买 nike

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

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/

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