c - OpenMP shared variable seems to be private -


i don't understand why in code thread 0 has n = 1 while other ones have n = 0 shared n:

int main() {     int n, tid;      #pragma omp parallel shared(n) private(tid)     {             tid = omp_get_thread_num();             n = 0;              if (tid == 0)             {                     n++;             }              printf("i'am %d, n: %d\n", tid, n);     }      return 0;  } 

output:

i'am 5, n: 0 i'am 7, n: 0 i'am 0, n: 1 i'am 2, n: 0 i'am 4, n: 0 i'am 3, n: 0 i'am 6, n: 0 i'am 1, n: 0 

i'am new omp library. i'am working through ssh on cluster 8 nodes, can problem?

thank you.

you practically resetting n 0 each thread. thread tid==0 increment n prior printing. here, may encounter program print

i'am 0, n: 0

instead of expected

i'am 0, n: 1

since produced so-called race condition.

if intend initialize n 0 @ beginning of runtime, need initialize n earlier, e.g. prior starting parallel section:

n = 0;  #pragma omp parallel shared(n) private(tid) {         tid = omp_get_thread_num();          if (tid == 0)         {                 n++;         }          printf("i'am %d, n: %d\n", tid, n); } 

note, however, state of n in printed list random again, since can never sure when thread 0 increments value of n equal 1.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -