#include <stdio.h>
#include <omp.h>
static double num = 1;
double func1(){
for (int i=0; i<100; i ){
num = 1;
for (int j=0; j<100; j ){
num -= 1;
for (int k=0; k<100; k ){
num = 1;
if (num == 1000){
return num;
}
}
}
}
}
int main(){
#pragma omp parallel num_threads(10)
{
double num2 = func1();
}
printf("%lf", num2);
return 0;
}
/*
Compiles with: gcc fileName.c -o fileName -openmp
Executes with: ./fileName
// Note: in the terminal
*/
The above code when compiled gets stuck in an endless loop or something it does not exit. I tried "#pragma omp parallel for" but it throws out an error. I wonder if it works if I collapse the loop into one. Would really appreciate help. Thanks.`
CodePudding user response:
This is a no-show: all your threads try updating simultaneously the num
global variable. This is a so-called "race condition". Not only the final result is unpredictable, but this slows down everything.
As a rule of thumb, in multithreaded code do not use global and/or static variables, unless you really know what you are doing.
CodePudding user response:
Your code has as race condition. Interesting, adding reduction( :num)
to the parallel clause doesn't solve much. You break at 1000
but I get results (if I make num2
global to the main) that are approximately 1000 nthreads
. Big question is: what is this supposed to do?
For the rest I have some comments: 1. It can not compile because num2 is local. 2. Your function generates a warning that there are code paths that return void. 3. Why do you return num when it's global anyway? 4. Do not use global variables. 5. Your printf is missing a newline.