4

I tried to write a small C program to figure out how does OpenMP works. This example is supposed to compute the sum of 1 to 1000; however, it printed out 0 in the terminal. I can only get the desired result after commenting the #pragma stuff out. Can someone possibly tell me the reason?

This guide says that #pragma omp for divides the work of the for-loop among the threads of the current team. It does not create threads, it only divides the work amongst the threads of the currently executing team. So we should only have one main thread throughout the execution, correct?

#include <stdio.h> int main() { int n, sum = 0; #pragma omp for for (n = 0; n <1000; n++) { sum += n; } printf("%d\n"); return 0; } 

1 Answer 1

5

You have several issues for such a simple example...

1) You are not starting a parallel region. To do this, use omp parallel for instead of just omp for.

2) Your variables are not being made private to each thread working on your different loops. So each thread is over-writing each other thread's version of the variables. Specifically n needs to be made private.

3) You are attempting to sum one shared variable across multiple threads. This must be done with the reduction clause.

4) You're not printing anything actually out. Your printf() syntax as-is will not print the proper result ever.

So your example really should look like:

int n, sum = 0; #pragma omp parallel for private(n) reduction(+:sum) for (n = 0; n < 1000; n++) { sum += n; } printf("%d\n", sum); 

I'd strongly suggest you look up a basic OpenMP tutorial (either online or in a book). The first 3 problems would have been obvious with just a little bit of research.

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

5 Comments

It's my first day starting to learn parallel programing, thank you for pointing out those errors. Do you have any books or slides available online to recommend? Most of the materials that I found assume readers having some related experience in this field..
@YufanFei this is a good tutorial that I've referenced to a few times. Although the best book on this in my opinion is this one. Very accessible to new people.
Loop variables in the associated for-loops are predetermined to be private, therefore private(n) is redundant.
@HristoIliev Technically true. But I would never suggest to someone just learning parallel programming to rely on implicit behavior. Until you understood why and how everything works, being verbose and going through the motions of understanding what's going on is the best course of action.
@NoseKnowsAll Thanks for your suggestion. It really helps!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.