在C ++ OpenMP中为每个线程定义一个优先级队列

时间:2017-02-17 19:00:15

标签: c++ multithreading openmp

我在OpenMP中并行化一个for循环,我正在尝试为每个线程创建一个优先级队列,这样我就可以更新与该线程对应的优先级队列,所以我尝试这样的事情:

#include <queue>
#include <omp.h>

void test(){

  // I need a priority queue per thread
  // std::priority_queue<int> q_per_thread;

  # pragma omp parallel for num_threads(10)
  for(int i = 0; i < 100; i++){
      // push i to the queue corresponding to the thread
  }

}

这可能吗?

2 个答案:

答案 0 :(得分:2)

如果优先级队列的范围只是并行区域,那么您可以编写此代码以使其显式化(并避免构建线程数和令人不快的num_threads(10)子句和omp_get_thread_num()电话)这样的事情

#pragma omp parallel
{
    std::priority_queue<int> q;
#pragma omp for 
    for (int i = 0; i < 100; i++)
    {
        // push i to the queue corresponding to the thread
        q.push(i);
        ... whatever else you're intending to do with the q ...
    }
 }

答案 1 :(得分:1)

您需要一组优先级队列,因为您将在并行OpenMP部分中拥有多个线程:

 // I need a priority queue per thread
 std::vector<std::priority_queue<int>> q_per_thread(10);

 # pragma omp parallel for num_threads(10)
 for(int i = 0; i < 100; i++){
    // push i to the queue corresponding to the thread
    q_per_thread[omp_get_thread_num()].push(i);
 }

编辑:修复它