如何确保动态分配的数组在openmp中是私有的

前端之家收集整理的这篇文章主要介绍了如何确保动态分配的数组在openmp中是私有的前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在C上使用openMP在 linux机器上使用gcc.在一个openmp并行循环中,我可以将静态分配的数组声明为私有的.考虑代码片段:
  1. int a[10];
  2. #pragma omp parallel for shared(none) firstprivate(a)
  3. for(i=0;i<4;i++){

一切都按预期工作.但是如果我分配一个动态的,

  1. int * a = (int *) malloc(10*sizeof(int));
  2. #pragma omp parallel for shared(none) firstprivate(a)

a(至少[1 … 9])的值不受保护,但如果它们是共享的.这是可以理解的,因为在pragma命令中没有什么可以告诉omp数组a需要是私有的多大.如何将这些信息传递给openmp?如何将整个动态分配的数组声明为私有?

解决方法

我不认为你这样做 – 我做了什么来解决这个问题是使用一个并行区域#pragma omp parallel shared(…)private(…)并在并行区域内动态分配数组.尝试这个:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <malloc.h>
  4.  
  5. /* compile with gcc -o test2 -fopenmp test2.c */
  6.  
  7. int main(int argc,char** argv)
  8. {
  9. int i = 0;
  10. int size = 20;
  11. int* a = (int*) calloc(size,sizeof(int));
  12. int* b = (int*) calloc(size,sizeof(int));
  13. int* c;
  14.  
  15. for ( i = 0; i < size; i++ )
  16. {
  17. a[i] = i;
  18. b[i] = size-i;
  19. printf("[BEFORE] At %d: a=%d,b=%d\n",i,a[i],b[i]);
  20. }
  21.  
  22. #pragma omp parallel shared(a,b) private(c,i)
  23. {
  24. c = (int*) calloc(3,sizeof(int));
  25.  
  26. #pragma omp for
  27. for ( i = 0; i < size; i++ )
  28. {
  29. c[0] = 5*a[i];
  30. c[1] = 2*b[i];
  31. c[2] = -2*i;
  32. a[i] = c[0]+c[1]+c[2];
  33.  
  34. c[0] = 4*a[i];
  35. c[1] = -1*b[i];
  36. c[2] = i;
  37. b[i] = c[0]+c[1]+c[2];
  38. }
  39.  
  40. free(c);
  41. }
  42.  
  43. for ( i = 0; i < size; i++ )
  44. {
  45. printf("[AFTER] At %d: a=%d,b[i]);
  46. }
  47. }

对我来说,产生了与我早期实验程序相同的结果:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <malloc.h>
  4.  
  5. /* compile with gcc -o test1 -fopenmp test1.c */
  6.  
  7. int main(int argc,sizeof(int));
  8.  
  9. for ( i = 0; i < size; i++ )
  10. {
  11. a[i] = i;
  12. b[i] = size-i;
  13. printf("[BEFORE] At %d: a=%d,b[i]);
  14. }
  15.  
  16. #pragma omp parallel for shared(a,b) private(i)
  17. for ( i = 0; i < size; i++ )
  18. {
  19. a[i] = 5*a[i]+2*b[i]-2*i;
  20. b[i] = 4*a[i]-b[i]+i;
  21. }
  22.  
  23. for ( i = 0; i < size; i++ )
  24. {
  25. printf("[AFTER] At %d: a=%d,b[i]);
  26. }
  27. }

猜测我会说,因为OpenMP不能推导出数组的大小不能是私有的 – 只有编译时数组可以这样做.当我尝试私有一个动态分配的数组时,我会得到segfaults,大概是因为访问冲突.在每个线程上分配数组,就像您使用pthreads编写的一样,这是有道理的,解决了这个问题.

猜你在找的C&C++相关文章