Domanda

I am new to openmp and am playing around with some stuff for a school project. I was trying to make my program run a little faster by using atomic instead of critical. I have this snippet of code at the end of one of my for loops.

  if(prod > final_prod)
  {
    #pragma omp atomic
    final_prod = prod;
  }

Although when I do this I get the error below (if I use critical the program compiles fine)

error: invalid form of ‘#pragma omp atomic’ before ‘;’ token
     final_prod = prod;
                      ^

From what I've learned so far you can use atomic instead of critical for usually something that can be executed in a few machine instructions. Should this work? And what is the main difference between using atomic vs critical?

È stato utile?

Soluzione

According to the docs here you can only use atomic with certain statement forms:

enter image description here

Also, make sure the comparison is inside the critsec! So I assume you cannot have what you want, but if you had

if(prod > final_prod) // unsynchronized read
{
  #pragma omp critical
  final_prod = prod;
}

it would still be data race

Altri suggerimenti

You can only use the following forms of operators using #pragma omp atomic:

  1. x++, x-- etc.
  2. x += a;, x *=a etc.

Atomic instructions are usually faster, but have a very strict syntax.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top