quartz
quartz

Reputation: 757

How to do task parallelization having some for loops in c using openmp?

I have a c program as below:

int a[10];
int b;

for(int i = 0; i < 10; i++)

     function1(a[i]);
function1(b);

Now I want to parallelize all these 11 calls of function function1(). How can I do this using openmp?

I have tried

#pragma omp parallel sections
{
#pragma omp section
#pragmal omp parallel for
for(int i = 0; i < 10; i++)
     function1(a[i]);
#pragma omp section
function1(b);
}

But the above code doesn't seem to work. EDIT: Please read function1(b) as some different function, ie function2(b).

Upvotes: 0

Views: 111

Answers (2)

ugoren
ugoren

Reputation: 16441

A simple way, that doesn't depend on OpemMP, is to add b to the a array.
This way, you have a single loop to parallelize.
Just make a 11 ints long, and put the value of b in the last one.

In a more general case (assuming the members of a are not integers, but something larger), you may want to change function1 to get a pointer. Then build another array, of 11 pointers. Set 10 to point to cells of a, the last to b.

In an even more general case, the function called for b is a different one (possibly with entirely different parameters). In this case, you can still use one loop:

for (i=0; i<11; i++) {
    if (i<10) {
        function1(a[i]);
    } else {
        function2(b);
    }
}

Upvotes: 1

Win32
Win32

Reputation: 1149

The easiest way is using the parallel for pragma:

#pragma omp parallel for
for(int i = 0; i < 10; i++)
    function1(a[i]);

Remember that you must turn on the appropiate switch for your compiler to enable OMP support. In GCC, for example, that switch is -fopenmp

Upvotes: 1

Related Questions