2

Code for test(my cpu has 6 cores, you can replace omp_set_num_threads(12) to omp_set_num_threads(4) if you don't have that much cores:

#include <stdio.h>
#include <omp.h>
#include<time.h>
int main()
{
    int A;
    omp_set_num_threads(12);
    clock_t begin, end;
    begin = clock();
#pragma omp parallel for firstprivate(A) lastprivate(A)
    for (int i = 0; i < 1000000000; i++)
    {
        A = i;
        int num = omp_get_thread_num();
        //printf("Thread %i got %d\n", num, A);
    }
    end = clock();
    printf("At the end, A will be: %i\n", A);
    printf("Time: %f", (double)(end - begin) / CLOCKS_PER_SEC);
    return 0;
}

The result stays the same if I remove firstprivate(A), use lastprivate(A) only for this loop, so I am curious about if I can use only lastprivate(A) instead of firstprivate(A) lastprivate(A) in any cases.

Environment:

Windows 10 + Visual Studio 2019, C

Yiling Liu
  • 666
  • 1
  • 6
  • 21
  • 1
    `firstprivate` is only meant to initialize the `private` local variable with the value of the shared one upon entry to the region it applies to. Here, your very first action in the `parallel` region is to assign a value to `A`, so having declared it `firstprivate` is useless. – Gilles Jul 14 '20 at 12:34
  • Oh I see.. thanks. Now we can close this problem because my code is not appropriate. I change `A = i` into `A += i`. Now both firstprivate and lastprivate is needed – Yiling Liu Jul 14 '20 at 12:46
  • `firstprivate` and `lastprivate` are orthogonal. You are free to use one, both, or none of them. – Hristo Iliev Jul 15 '20 at 10:40

0 Answers0