How do I parallelize a for loop through a C++ std::list using OpenMP?

前端 未结 5 1218
刺人心
刺人心 2020-12-01 06:25

I would like to iterate through all elements in an std::list in parallel fashion using OpenMP. The loop should be able to alter the elements of the list. Is there a simple s

5条回答
  •  一向
    一向 (楼主)
    2020-12-01 07:05

    Without using OpenMP 3.0 you have the option of having all threads iterating over the list:

    std::list::iterator it;
    #pragma omp parallel private(it)
    {
       for(it = list1.begin(); it!= list1.end(); it++)
       {
          #pragma omp single nowait
          {
             it->compute();
          }
       } 
    } 
    

    In this case each thread has its own copy of the iterator (private) but only a single thread will access a specific element (single) whereas the other threads will move forward to the next items (nowait)

    Or you can loop once to build a vector of pointers to be then distributed among threads:

    std::vector< T*> items;
    
    items.reserve(list.size());
    //put the pointers in the vector
    std::transform(list.begin(), list.end(), std::back_inserter(items), 
                   [](T& n){ return &n; }
    );
    
    #pragma omp parallel for
    for (int i = 0; i < items.size(); i++)
    {
      items[i]->compute();
    }
    

    Depending on your specific case one or the other can be faster. Testing which one suits you better is easy.

提交回复
热议问题