## OpenMP Tutorial – firstprivate and lastprivate

Here I will consider firstprivate and lastprivate. Recall one of the earlier entries about private variables. When a variable is declared as private, each thread gets a unique memory address of where to store values for that variable while in the parallel region. When the parallel region ends, the memory is freed and these variables no longer exist. Consider the following bit of code as an example:

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

int main(void){
int i;
int x;
x=44;
#pragma omp parallel for private(x)
for(i=0;i<=10;i++){
x=i;
}
printf("x is %d\n", x);

}


Yields…

Thread number: 0     x: 0
x is 44


You’ll notice that x is exactly the value it was before the parallel region.

Suppose we wanted to keep the last value of x after the parallel region. This can be achieved with lastprivate. Replace private(x) with lastprivate(x) and this is the result:

Thread number: 3     x: 9
x is 10


Notice that it is 10 and not 8. That is to say, it is the last iteration which is kept, not the last operation. Now what if we replace lastprivate(x) with firstprivate(x). What do you think it will do? This:

Thread number: 3     x: 9