2017-02-17 25 views
1

我在OpenMP中並行化一個for循環,我試圖爲每個線程創建一個優先級隊列,這樣我就可以更新對應於線程的優先級隊列,所以我嘗試了類似這樣的東西:在C++ OpenMP中爲每個線程定義一個優先級隊列

#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 
    } 

} 

這可能嗎?

+1

在並行循環之後,你想對隊列中的數據做什麼? – Zulan

+0

爲什麼每個線程*和*循環都有一個隊列?循環用於數據並行性,其中*不*必須*不必關心處理數據的線程。你不應該看*任務*並行或代理嗎? –

回答

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); 
} 

編輯:固定它

+1

這創建了每個線程的隊列私有向量... – Zulan

+0

在我看來,這個答案http://stackoverflow.com/a/42341174/2542702更好。 –

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 ... 
    } 
}