开放MP:具有共享元素的私有结构?

时间:2020-02-26 00:09:09

标签: openmp

以下可能吗?

编辑:最小的工作示例:

#include <omp.h>
#include <stdio.h>

struct foo
{
        int a;
        int b;
};

int main(int argc, char ** argv)
{
  struct foo outerFoo;
  int * p = &outerFoo.a;

  outerFoo.a = 1;

  printf("outerFoo @ %p, a=%d\n", &outerFoo, outerFoo.a);

#pragma omp parallel private(outerFoo), shared(p)
  {
    printf("Thread %d: outerFoo @ %p, a=%d, p = %p,p->:%d\n",
           omp_get_thread_num(),
           &outerFoo, outerFoo.a,p,*p);

#pragma omp critical // i know i can use atomic here
    {
        *p=*p+1;
    }
  }

  printf("a:%d\n",outerFoo.a);
  return 0;
}

1 个答案:

答案 0 :(得分:1)

您写的东西肯定是可能的。由于您还没有告诉我们这是什么,我们无法确定是否满足您的要求!

我强烈怀疑它不会,因为它将在每个线程中生成somestruct的新的未初始化实例,以及指向外部作用域实例的共享指针。

考虑此代码,该代码与您的代码实际上相同,但可编译

#include <omp.h>
#include <cstdio>

class foo
{
public:
  int a;
  int b;
  foo() : a(0), b(1) {}
};

int main(int argc, char ** argv)
{
  foo outerFoo;
  int * p = &outerFoo.a;

  outerFoo.a = 27;

  printf("outerFoo @ %p, a=%d, b=%d\n", &outerFoo, outerFoo.a, outerFoo.b);
#pragma omp parallel private(outerFoo), shared(p)
  {
    printf("Thread %d: outerFoo @ %p, a=%d, b=%d, p = %p\n",
           omp_get_thread_num(),
           &outerFoo, outerFoo.a, outerFoo.b,p);
  }

  return 0;
}

它打印出这样的内容

OMP_NUM_THREADS=4 ./a.out
outerFoo @ 0x7fffffffd080, a=27, b=1
Thread 0: outerFoo @ 0x7fffffffcb80, a=0, b=1, p = 0x7fffffffd080
Thread 3: outerFoo @ 0x2aaaacf4fa80, a=0, b=1, p = 0x7fffffffd080
Thread 2: outerFoo @ 0x2aaaacb4da80, a=0, b=1, p = 0x7fffffffd080
Thread 1: outerFoo @ 0x2aaaac74ba00, a=0, b=1, p = 0x7fffffffd080

所以您可以看到这种情况。该类有一个外部实例,而内部有四个实例。它们都有所有的struct字段。