The question about using OpenMP taskloop feature in gcc

Xi Ruoyao ryxi@stu.xidian.edu.cn
Tue Nov 21 08:50:00 GMT 2017


On 2017-11-21 15:49 +0800, Nan Xiao wrote:
> Hi all,
> 
> Greetings from me!
> 
> I try to test OpenMP taskloop feature, so write a simple program:
> 
> #include <omp.h>
> #include <stdio.h>
> 
> int main(void) {
>     #pragma omp parallel for
>     for (auto i = 0; i < 10; i++) {
>           int sum = 0;
>           #pragma omp taskloop shared(sum)
>           for (auto j = 0; j < 1000000; j++) {
>                  sum += j;
>            }
>            printf("%d\n", sum);
>      }
>      return 0;
> }
> 
> Build with g++:
> 
> $ g++ -fopenmp -std=c++11 hello.cpp
> 
> Run it:
> 
> $ ./a.out
> 1306095808
> -282666465
> -1041115334
> 1291875106
> 1458947340
> -1324830858
> 1186345979
> -505484990
> 1660339799
> 93719282
> 
> We can see it generates the gibberish. But build using clang++:
> 
> $ clang++ -fopenmp -std=c++11 hello.cpp
> 
> Every time it will generate the same result:
> 
> $ ./a.out
> 1783293664
> 1783293664
> 1783293664
> 1783293664
> 1783293664
> 1783293664
> 1783293664
> 1783293664
> 1783293664
> 1783293664
> 
> Since I am not an expert of OpenMP, I am not sure whether it's the
> coincidence of
> clang version, or it should be a bug of gcc.
> 
> Could anyone give some comments? Thanks very much in advance!

There are two bugs in your code.  First, signed overflow is an undefined
behaviour and may generate arbitary result.  Second, the access to shared
variable sum is racing, the result may vary with scheduling.
> 
> Best Regards
> Nan Xiao
-- 
Xi Ruoyao <ryxi@stu.xidian.edu.cn>
School of Aerospace Science and Technology, Xidian University



More information about the Gcc-help mailing list