1

I have a for loop in the following code.

int min = -1;
int pos;
int array[100];

for(i = 0; i < 100; i++){
  if(array[i] < min || min == -1){
    min = array[i];
    pos = i;
  }
}

I think that the following code is a correct implementation with openMP but it is too slow.

int min = -1;
int pos;
int array[100];

#pragma omp parallel for default(none) shared(array, min) 
for(i = 0; i < 100; i++){
#pragma omp critical
  {
    if(array[i] < min || min == -1){
      min = array[i];
      pos = i;
    }
  }
}

I think that could be data hazards if i put the critical section inside the condition instead of outside. There is a smart way to implement it? Some suggestions?

24
  • 4
    min = -1 shouldn't this be min == -1? Commented Mar 31, 2015 at 11:49
  • 1
    correct this portion.. if(array[i] < min || min = -1) Commented Mar 31, 2015 at 12:01
  • 1
    If the whole body of the loop is a critical section, the parallel pragma is completely useless. Commented Mar 31, 2015 at 13:10
  • 1
    Of course it's worse than the serial implementation. It is serial, but adds thread creation and synchronisation overhead. Do you really think creating a new thread is faster than reading 100 ints? You might start to see speed up if you properly parallelized the loop and used it on a much larger array. Commented Mar 31, 2015 at 14:05
  • 1
    @Tigran: Done. Tell me if you find anything wrong with it. Commented Mar 31, 2015 at 14:36

1 Answer 1

2

I've coded up a small parallel search function. I've only tested that it compiles, but I believe the principle is sound:

#include <stddef.h>
#define MINDIVIDE 1024

int parallelminsearch(int const *array, size_t size)
{
  int minimum;
  if (size < MINDIVIDE)
    {
      minimum = array[0];
      for (size_t i = 1; i < size; i++)
        {
          if (array[i] < minimum)
          minimum = array[i];
        }
      return minimum;
    }
  int pmin[2];
  #pragma omp parallel for
  for (size_t i = 0; i < 2; i++)
    {
      pmin[i] = parallelminsearch(&array[i*size/2], (size+1)/2);
    }
  minimum = (pmin[0] < pmin[1])?pmin[0]:pmin[1];
  return minimum;
}
Sign up to request clarification or add additional context in comments.

Comments

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.