5

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 ?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

In practice, int should be aligned and would turn out to be atomic. The race condition could affect performance even though it shouldn't result in errors if the value doesn't change.
I too would be very surprised to see the program producing a wrong result in practice. Nevertheless it's unspecified, implementation defined and not portable.
@Zulan: Thank you. In practice I've never gotten a "bad" value for numthreads but today while writing this a doubt arose which has been put to rest. +1 to tim18 for bringing the performance issue up. I will read the memory model as soon as I get time. Thank you again for your efforts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.