Gaurav Saxena
Gaurav Saxena

Reputation: 729

Shared variables in OpenMP

I have a very basic question (maybe stupid) regarding shared variables in OpenMP. Consider the following code:

void main()
{
int numthreads;
#pragma omp parallel default(none) shared(numthreads)
 {
  numthreads = omp_get_num_threads();
  printf("%d\n",numthreads);
 }
}

Now the value of numthreads is the same for all threads. is there a possibility that since various threads are writing the same value to the same variable, the value might get garbled/mangled ? Or is this operation on a primitive datatype guaranteed to be atomic ?

Upvotes: 5

Views: 15061

Answers (1)

Zulan
Zulan

Reputation: 22660

As per the standard, this is not safe:

A single access to a variable may be implemented with multiple load or store instructions, and hence is not guaranteed to be atomic with respect to other accesses to the same variable. [...] If multiple threads write without synchronization to the same memory unit, including cases due to atomicity considerations as described above, then a data race occurs. [...] If a data race occurs then the result of the program is unspecified.

I strongly recommend reading 1.4.1 Structure of the OpenMP Memory Model. While it's not the easiest read, it's very specific and quite clear. By far better than I could describe it here.

Two things need to be considered about shared variables in OpenMP: atomicity of access and the temporary view of memory.

Upvotes: 6

Related Questions