Pergunta

I'm trying to parallelize switch ... case (c++) using OpenMP directive, but despite my best efforts, the code goes slower than normal sequential execution.

I have used #pragma parallel, #pragma sections, I have tried to rewrite the switch case with an if ... else statement but with no good result ...

switch (number) {
  case 1:
    f1();
    break;
  case 2:
    f2();
    break;
  case 3:
    f3();
    break;
  case 4:
    fn();
    break;
}

Then there is a second problem, OpenMP won't break or return.

Foi útil?

Solução

The switch cases cannot be implemented in Openmp, just by adding pragma's like parallel, section. The threads running along the parallel section divide work among themselves via the loop index or else they do the same work in a conditional loop. Openmp section needs to know either how many elements it needs to work on or a master condition which determines start and end. You want to make the input section as parallel instead of the functions (f1, f2, .. fn), so I am guessing you are processing a lot of "number". One way is to collect these numbers in a array/vector. Then, you can make a parallel for along this vector/array, calling the corresponding function.

while(some_condition_on_numbers)
{
    // Collect Numbers in a vector / some array    
}

#pragma omp parallel for
for(int counter = 0; counter < elements_to_process; counter++)
{
    F(array_of_number[counter]);
}

F(int choice)
{
    if(choice = 1) {f1(); }
    if(choice = 2) {f2(); }
    ..
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top