I want to parallelize a loop in a class member function. However there are two errors in the code:
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
}
}
}
}
How to explain these errors and solve the problems? Thanks and regards!
For the second error, The OpenMP specification doesn't allow you to break out of a parallel for loop, or throw exceptions, because of the parallel nature. Instead, see the workaround solution on this blog: http://www.thinkingparallel.com/2007/06/29/breaking-out-of-loops-in-openmp/
For the first error, took me a while to dig up what is actually going on - I think this explains it:
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.
from http://www.viva64.com/content/articles/parallel-programming/?f=32_OpenMP_traps.html&lang=en&content=parallel-programming
Basically I don't think you can use class-level variables as private without making copies of them. Is there any reason you can't use a variable within the scope of your function?
精彩评论