How to use openmp with break in while loop

I want to use openmp to speed up my code like below.

The code is just an explanation of operations, not real ones.

Iterator iterator(records);
while(iterator.next())
{
    int current_id = iterator.current_row_index();
    bool result = index.find(records[current_id])
    if (result == false)
        if (index.insert(records[current_id]) == false)
            break;
}
return iterator.current_row_index();

      

The index is shared by all threads.

Here are some thoughts from me:

  • using omp parallel directive, make sure threads are executed in order.
  • using the critical omp directive to control the iterator.
  • using the critical omp directive to search the index and insert into the index.

but I really doubt the acceleration as almost the entire operation is in a critical state.

Are there any tips for speeding up code usage with openmp?

Thank!

+3


source to share


1 answer


Answering the title of the question and assuming there were no other problems (discussed below), a generic while loop with a break from the forward iterator could be translated like this:

Iterator iterator(records);
#pragma omp parallel
{
    #pragma omp single nowait
    {
        while(iterator.next())
        {
            int current_id = iterator.current_row_index();
            #pragma omp task firstprivate(current_id)
            {
                if ( should_stop(current_id)) ) {
                    // below requires OpenMP 4.0
                    #pragma omp cancel parallel
                }
            }
        }
    }
}

      



However, there are more complex issues in your question that really deserve separate questions.

  • The use of a table index

    assumes that it is not thread safe. So you cannot safely access and paste it at the same time. And since this is the only work for the while loop, there is no point in making it parallel unless you switch to a parallel hash table like the concurrent_unordered_map presented for example., , boost

  • It is unclear when insert might return false and why you need the row index when it does. Probably, after switching to a different table implementation, this would not be necessary at all. Otherwise, as a rule, several threads can have a "response" to your state at the same time, and you have to synchronize them and reduce to the same result. The easiest OMP-ish way is to use the critical section to select and store the result, otherwise there is a danger of introducing a race condition into the program.

+4


source







All Articles