0

I am currently learning about OpenMP. As default variables declared outside of the parallel region are public, where as variables inside of a parallel region are private. Also stack variables from inside the parallel regions are private.

double A[10];
int index[10];
#pragma omp parallel
{
 work(index);
}
printf(%d\n”,index[0]);

But why is "index" on the above example public for each thread? Shouldn't it be private, since its put on the stack, and stack variables are private?

Thanks in advance

  • Why would you think that "stack variables are private"? Do you mean "shared" if you write "public"? Are you, perhaps, suffering from the same misunderstandings as discussed in [this question](https://stackoverflow.com/q/48135794/620382)? – Zulan Jan 22 '19 at 12:14
  • Well I am learning for my exam, and on the slides there is a line "But not everything is shared - Stack variables in C functions called from parallel regions are PRIVATE". Sorry, yes I mean shared when I say public – User20139023 Jan 22 '19 at 12:16

1 Answers1

1

The statement

Stack variables in C functions called from parallel regions are private

is true, but you need to differentiate in your case. First,

int index[10];
#pragma omp parallel
{
    // index is a shared variable here
    work(index);
}

But when it comes to the function you call, imagine:

void work(int* passed_index)
{
    ...
}

passed_index - the pointer - is in fact a private variable within work. You can change the pointer, and no other thread will notice.

But the data pointed to by *passed_index is still shared.

Zulan
  • 21,896
  • 6
  • 49
  • 109
  • Aaah know I understand. So I could change the pointer of passed_index, but when I try to, lets say do passed_index[0] = 1; This would have an effect on the other threads, right? Also when I define a variable inside of work() it gets private I guess – User20139023 Jan 22 '19 at 12:27
  • You can stil safely work on different *elements* of the array (e.g. thread `i` on `passed_index[i]`). And yes, variables defined within `work` are private, but of course you can't just `int* foo = passed_index` - that would still be a pointer to shared data. – Zulan Jan 22 '19 at 12:58