【问题标题】:Define a priority queue per thread in C++ OpenMP在 C++ OpenMP 中为每个线程定义一个优先级队列
【发布时间】:2017-02-17 19:00:14
【问题描述】:

我在 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
  }

}

这可能吗?

【问题讨论】:

  • 并行循环后队列中的数据要做什么?
  • 为什么每个线程都有一个队列循环?循环用于数据并行,您不应该必须关心处理数据的线程。您不应该关注 task 并行性或代理吗?

标签: c++ multithreading openmp


【解决方案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);
 }

编辑:修复它

【讨论】:

【解决方案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 ...
    }
 }

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 2012-03-03
    • 1970-01-01
    • 2017-06-13
    • 2023-04-02
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多