A simple OpenMP program:
#include <omp.h>
#include <iostream>
int main() {
int var = 0;
int var2 = 0;
#pragma omp parallel private(var) shared(var2)
{
var = 1;
int tid = omp_get_thread_num();
printf("Inside the parallel region, var gets modified by thread #%d to %d\n",tid,var);
if(tid == 0)
var2 = var;
}
printf("Outside the parallel region, var = %d\n", var);
printf("Outside the parallel region, var2 = %d\n", var2);
}
Result:
Inside the parallel region, var gets modified by thread #3 to 1
Inside the parallel region, var gets modified by thread #0 to 1
Inside the parallel region, var gets modified by thread #6 to 1
Inside the parallel region, var gets modified by thread #1 to 1
Inside the parallel region, var gets modified by thread #5 to 1
Inside the parallel region, var gets modified by thread #7 to 1
Inside the parallel region, var gets modified by thread #2 to 1
Inside the parallel region, var gets modified by thread #4 to 1
Outside the parallel region, var = 0
Outside the parallel region, var2 = 1
What I want to do is to set the value of var
to the last modified value inside the parallel region.
Since it's not a #pragma omp for
loop, lastprivate
is invalid to use.
Outside the parallel region, var
gets its original value, 0. A trick is to use a shared variable var2
to stored the modified value from the master thread.
But this increases the overhead and doesn't seem to be an elegant approach, and in case I want to get the value modified by the last thread, not the master, (e.g. to find out which thread finishes last), then this trick will not work.
I'm quite new to OpenMP, so I might be missing something. In case I'm not, is there any way to get over this tricky thing?
Thank you very much.
Edit: My question is about how to remain the last value of a private variable after the parallel region finishes. Or if you could explain why lastprivate
is conceptually not valid to use in a #pragma omp parallel
, I'll take that as a perfect answer.