我在C上使用openMP在
linux机器上使用gcc.在一个openmp并行循环中,我可以将静态分配的数组声明为私有的.考虑代码片段:
- int a[10];
- #pragma omp parallel for shared(none) firstprivate(a)
- for(i=0;i<4;i++){
一切都按预期工作.但是如果我分配一个动态的,
- int * a = (int *) malloc(10*sizeof(int));
- #pragma omp parallel for shared(none) firstprivate(a)
a(至少[1 … 9])的值不受保护,但如果它们是共享的.这是可以理解的,因为在pragma命令中没有什么可以告诉omp数组a需要是私有的多大.如何将这些信息传递给openmp?如何将整个动态分配的数组声明为私有?
解决方法
我不认为你这样做 – 我做了什么来解决这个问题是使用一个并行区域#pragma omp parallel shared(…)private(…)并在并行区域内动态分配数组.尝试这个:
- #include <stdio.h>
- #include <stdlib.h>
- #include <malloc.h>
- /* compile with gcc -o test2 -fopenmp test2.c */
- int main(int argc,char** argv)
- {
- int i = 0;
- int size = 20;
- int* a = (int*) calloc(size,sizeof(int));
- int* b = (int*) calloc(size,sizeof(int));
- int* c;
- for ( i = 0; i < size; i++ )
- {
- a[i] = i;
- b[i] = size-i;
- printf("[BEFORE] At %d: a=%d,b=%d\n",i,a[i],b[i]);
- }
- #pragma omp parallel shared(a,b) private(c,i)
- {
- c = (int*) calloc(3,sizeof(int));
- #pragma omp for
- for ( i = 0; i < size; i++ )
- {
- c[0] = 5*a[i];
- c[1] = 2*b[i];
- c[2] = -2*i;
- a[i] = c[0]+c[1]+c[2];
- c[0] = 4*a[i];
- c[1] = -1*b[i];
- c[2] = i;
- b[i] = c[0]+c[1]+c[2];
- }
- free(c);
- }
- for ( i = 0; i < size; i++ )
- {
- printf("[AFTER] At %d: a=%d,b[i]);
- }
- }
对我来说,产生了与我早期实验程序相同的结果:
- #include <stdio.h>
- #include <stdlib.h>
- #include <malloc.h>
- /* compile with gcc -o test1 -fopenmp test1.c */
- int main(int argc,sizeof(int));
- for ( i = 0; i < size; i++ )
- {
- a[i] = i;
- b[i] = size-i;
- printf("[BEFORE] At %d: a=%d,b[i]);
- }
- #pragma omp parallel for shared(a,b) private(i)
- for ( i = 0; i < size; i++ )
- {
- a[i] = 5*a[i]+2*b[i]-2*i;
- b[i] = 4*a[i]-b[i]+i;
- }
- for ( i = 0; i < size; i++ )
- {
- printf("[AFTER] At %d: a=%d,b[i]);
- }
- }
猜测我会说,因为OpenMP不能推导出数组的大小不能是私有的 – 只有编译时数组可以这样做.当我尝试私有一个动态分配的数组时,我会得到segfaults,大概是因为访问冲突.在每个线程上分配数组,就像您使用pthreads编写的一样,这是有道理的,解决了这个问题.