Novice C
Novice C

Reputation: 1374

Openmp compiles, but "parallel for" isn't working as planned in C

I am working on Mac OSX 10.8.3, and I am programming in C. I am using bash as my shell and I am using gcc-mp-4.7 from macports, since I know the gcc from apple sometimes doesn't fully work with openmp. I have ran a few openmp files before and they typically work fine, however when I try to use the parallel for pragma, I doesn't work how I would think it would. An example of my .c file is below:

#include <omp.h>
#include <stdio.h>

int main (int argc, char *argv[]) {
    int n;
#pragma omp for
    for(n=0; n<100; ++n)
    {
        printf(" %d", n);
    }
    printf(".\n");
}

The output 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99., every single time (over 20 spams).

This shouldn't be happening if is it was running in parallel, there is nothing to protect the order like this. I believe it is obviously running in sequencial order ignoring the command to parallelize it.

Does anyone know what I might be doing wrong? Thanks for any help you can offer.

Upvotes: 1

Views: 1683

Answers (2)

meaning-matters
meaning-matters

Reputation: 22996

The outer most loop must include the parallel keyword to create a new pool of threads. So it should be:

#pragma omp parallel for

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 225212

  1. You should use #pragma omp parallel for:

    #pragma omp parallel for
    for(n=0; n<100; ++n)
    {
        printf(" %d", n);
    }
    

    or separate #pragma omp parallel and #pragma omp for, if you prefer:

    #pragma omp parallel
    {
        #pragma omp for
        for(n=0; n<100; ++n)
        {
            printf(" %d", n);
        }
    }
    

    The important thing to note is that #pragma omp parallel creates a pool of threads and #pragma omp for uses the created pool. If you don't have a pool, it's just going to be single-threaded.

  2. Make sure you're passing -fopenmp when building.

    Example:

    $ gcc -fopenmp example.c -o example
    $ ./example 
     13 0 78 65 52 39 14 1 26 91 79 66 53 40 15 2 27 92 80 
    67 54 41 16 3 28 93 81 68 55 42 17 4 29 94 82 69 56 43 
    18 5 30 95 83 70 57 44 19 6 31 96 84 71 58 45 20 7 32 
    97 85 72 59 46 21 8 33 98 86 73 60 47 22 9 34 99 87 74 
    61 48 23 10 35 88 75 62 49 24 11 36 89 63 76 50 25 12 
    37 90 64 77 51 38.
    

Upvotes: 2

Related Questions